Introduction
In this lab, we will learn how to create a custom React Hook called useOnWindowResize that will execute a callback whenever the window is resized. We will use the useRef() and useEffect() hooks to listen to the 'resize' event of the Window global object and clean up when the component unmounts. This Hook can be useful for creating responsive web applications that need to adjust to different screen sizes.
React useOnWindowResize Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
This code executes a callback function every time the window is resized. To implement it, you should follow these steps:
Create a variable called
listenerusing theuseRef()hook. This variable will store the reference to the listener.Use the
useEffect()hook andEventTarget.addEventListener()to listen to the'resize'event of theWindowglobal object. When the event is triggered, call thecallbackfunction.Clean up by removing any existing listeners with
EventTarget.removeEventListener()when the component unmounts.
Here's the code:
const useOnWindowResize = (callback) => {
const listener = React.useRef(null);
React.useEffect(() => {
if (listener.current) {
window.removeEventListener("resize", listener.current);
}
listener.current = callback;
window.addEventListener("resize", callback);
return () => {
window.removeEventListener("resize", callback);
};
}, [callback]);
};
const App = () => {
useOnWindowResize(() =>
console.log(`Window size: (${window.innerWidth}, ${window.innerHeight})`)
);
return <p>Resize the window and check the console.</p>;
};
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
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 useOnWindowResize Hook lab. You can practice more labs in LabEx to improve your skills.