Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
why does useEffect run once the window.innerWidth changes even though the second param in it is an empty array

useEffect in this code runs every time the window size changes, but the second parameter in useEffect is an empty array, I thought as long as the second parameter doesn't change compare to last time, the useEffect won't run

import React from "react"

export default function WindowTracker() {
    
    const [windowWidth, setWindowWidth] = React.useState(window.innerWidth)
    
    React.useEffect(() => {
        window.addEventListener("resize", function() {
            setWindowWidth(window.innerWidth)
        })
    }, [])
    
    return (
        <h1>Window width: {windowWidth}</h1>
    )
}

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It is not that useEffect runs, rather the registered event listener callback. useEffect indeed runs once and registers the event listener once. But then afterwards, the listener callback is called.

You told the event listener to listen to resize right? So you should expect it to be called any time resize happens.

Also if you return function from your effect, it will run when component unmounts (because of empty dependencies); you can use that to remove listener:

React.useEffect(() => {
  let cb = function () {
    setWindowWidth(window.innerWidth);
  };
  window.addEventListener("resize", cb);

  return () => {
    window.removeEventListener("resize", cb);
  };
}, []);
about 4 years ago · Juan Pablo Isaza Report

0

If you console.log inside of useEffect, you will see it will actually gets run only once. Basically you have set once the event listener for the resize event. But you still have the registered event listener in place, which works as it's supposed to.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!