Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda