Harnessing Window Properties and Events Using the useWindow Hook
Learn about the useWindow custom hook that enables dynamic adjustments to text or image appearance based on the browser window size.
We'll cover the following...
Refactoring useWindow hook
In the internal implementation of the useWindow custom hook, the React useState and useEffect hooks are utilized. A text or image can adjust its appearance based on the current browser window size. We experimented with this idea in The useEffect Hook Examples lesson.
Now the question is: can we abstract this idea out and apply it to anything on the screen as in a responsive design? Let's refactor the code a bit to come up with a custom useWindow hook:
const useWindow = (size = 0) => {// State variable to hold the current window widthconst [width, setWidth] = useState(0);useEffect(() => {// Function to handle resizing and update the width statefunction handleResize() {setWidth(window.innerWidth);}handleResize();// Event listener to update the width when the window is resizedwindow.addEventListener("resize", handleResize);// Cleanup function to remove the event listener when the component is unmountedreturn () => {window.removeEventListener("resize", handleResize);};}, [setWidth]); // Dependency array to ensure useEffect runs only when setWidth changes// Returning an array with the current window width and a boolean indicating whether it exceeds the specified sizereturn [width, width > size];};
The useWindow hook is taken out of our previous code and returns the current width of the screen. A useEffect is used to handle the initialization and cleanup of the system event upon a browser resize. During each screen resize, the window's innerWidth is stored in the ...