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.
React useOnWindowScroll Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This function executes a callback function every time the window is scrolled. To implement it:
- Use the
useRef()hook to create a reference variable,listener. - Use the
useEffect()hook andEventTarget.addEventListener()to listen to the'scroll'event of theWindowobject, and assign the listener reference tolistener.current. - 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.