React useOnWindowScroll Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to use the useOnWindowScroll hook in React to execute a callback whenever the window is scrolled. This hook allows us to add a scroll listener to the Window global object and remove it when the component unmounts. By using this hook, we can easily add custom scroll behavior to our React components.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StylingGroup(["`Styling`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StylingGroup -.-> react/css_in_react("`CSS in React`") subgraph Lab Skills react/jsx -.-> lab-38401{{"`React useOnWindowScroll Hook`"}} react/hooks -.-> lab-38401{{"`React useOnWindowScroll Hook`"}} react/css_in_react -.-> lab-38401{{"`React useOnWindowScroll Hook`"}} end

React useOnWindowScroll Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This function executes a callback function every time the window is scrolled. To implement it:

  1. Use the useRef() hook to create a reference variable, listener.
  2. Use the useEffect() hook and EventTarget.addEventListener() to listen to the 'scroll' event of the Window object, and assign the listener reference to listener.current.
  3. Use EventTarget.removeEventListener() to remove any existing listeners when the component unmounts.

Here's the code:

const useOnWindowScroll = (callback) => {
  const listener = React.useRef(null);

  React.useEffect(() => {
    if (listener.current) {
      window.removeEventListener("scroll", listener.current);
    }
    listener.current = () => {
      callback(window.pageYOffset);
    };
    window.addEventListener("scroll", listener.current);
    return () => {
      window.removeEventListener("scroll", listener.current);
    };
  }, [callback]);
};

To test the function, you can use it in a component like this:

const App = () => {
  useOnWindowScroll((scrollY) => console.log(`scroll Y: ${scrollY}`));
  return <p style={{ height: "300vh" }}>Scroll and check the console</p>;
};

ReactDOM.render(<App />, document.getElementById("root"));

This will log the vertical scroll position of the window every time it's scrolled.

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useOnWindowScroll Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like