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

205
Views
If I don't include a dependency in the useEffect array, will it be stale inside the closure?

Example:

const [foo, setFoo] = useState(0)
const [bar, setBar] = useState(0)

useEffect(() => { computation(foo, bar) }, [foo])

Will the value of bar inside the useEffect closure be stale? I'm asking because in one of my applications, I forgot to include the bar in the deps array and it seemed like it was still up to date.

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

0

Kind of, but not exactly. Staleness won't really be an issue, but whether the hook runs at all will be, because you're using useEffect rather than something like useCallback.

Using [foo] means that it'll run when foo changes. If your other code is set up that whenever bar changes, foo has or will also be changed as well, then when the component re-renders, the new values of both will then be seen by the effect hook.

But if you change bar without changing foo, the effect won't run at all.

You would have a stale closure problem, if bar changed when foo didn't, if you were using useCallback or useMemo, among others, because those save a value in an outer variable (which can then be called or passed to other components).

about 4 years ago · Juan Pablo Isaza Report

0

It won’t be stale within the effect, but the effect won’t re-run when bar changes.

about 4 years ago · Juan Pablo Isaza Report

0

Here you should understand when useEffect will work,

useEffect(() => { computation(foo, bar) } ) -> Will execute when any of the state in the component changes.

useEffect(() => { computation(foo, bar) }, [foo]) -> Will execute while mounting and during the 'foo' state changes.

useEffect(() => { computation(foo, bar) }, []) -> Will execute only while the component is mounting for the first time.

So if you don't include the dependency. The useEffect will be called every time any state of the component changes.

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!