Window Resize Listener using useEffect
WindowSize
component that listens to the window's resize
event and displays the current window size. Use the useEffect
hook to add and remove the event listener on mount and unmount, respectively. This exercise will help you understand how to use the useEffect
hook for managing side effects like event listeners and the importance of cleanup functions.Expectations
resize
event.Display the current window size.
Add the event listener when the component mounts.
Remove the event listener when the component unmounts.
Background
useEffect
to manage side effects like event listeners is an essential skill for React developers. Event listeners are common in real-world applications, and this exercise will help you learn how to use useEffect
for setting up and cleaning up event listeners in functional components.Solution Walkthrough for Window Resize Listener using useEffect
Spoiler Alert!
Don't read this unless you've already solved the problem.
windowSize
with the current window size:
We create a state variable windowSize
using the useState
hook and set its initial value to the current window size.const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight });
handleResize
function and add the event listener:
We use the useEffect
hook to set up the event listener when the component mounts. Inside useEffect
, we create a handleResize
function that updates the windowSize
state with the current window size. We then add the event listener to the window's resize
event.useEffect(() => {
const handleResize = () => {
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
};
window.addEventListener('resize', handleResize);
//...
}, []);
window.removeEventListener
. This cleanup function will be called when the component unmounts or if the effect is run again.useEffect(() => {
//...
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
windowSize
state variable to display the current window size in a paragraph element.<p>Window size: {windowSize.width} x {windowSize.height}</p>
useEffect
hook for managing side effects like event listeners, controlling when the effect runs using the dependency array, and handling cleanup with a returned cleanup function.