logo
logo

Window Resize Listener using useEffect

Medium

Window Resize Listener using useEffect

Medium
Create a
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

  • Listen to the window's
    resize
    event.
  • Display the current window size.

  • Add the event listener when the component mounts.

  • Remove the event listener when the component unmounts.

Background

Using
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.
Console
Submit
Solution
00:00

Solution Walkthrough for Window Resize Listener using useEffect

Solution Explanation

Initialize state variable
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 });
Create a
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);
  //...
}, []);
Return a cleanup function to remove the event listener: To ensure proper cleanup, we return a function that removes the event listener using
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);
  };
}, []);
Display the current window size: We use the
windowSize
state variable to display the current window size in a paragraph element.
<p>Window size: {windowSize.width} x {windowSize.height}</p>
This solution demonstrates the key concepts of using the
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.