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

131
Visualizações
Cannot Read Property of undefined Object in dependencies array in useEffect or useCallback in React

I have a useCallback() method below to improve the performance. This will be same logic with useEffect()

If I have a dependency which is router.asPath, but sometimes the router is null, which may cause the function crash.

In order to improvement performance, I do not want to put the whole object of router, as other fields changes, I do not want rerun the function.

Any suggest?

  const recordProduct = useCallback(() => {
    dispatch(setNextCollectionScroll(router.asPath, hit.handle))
  }, [dispatch, hit.handle, router])

The ideal dependency: [dispatch, hit.handle, router.asPath] But I have to do it now: due to the router object may be null: [dispatch, hit.handle, router]

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It is not clear what router are you using, and if you should look elsewhere, but in your simple case of checking dependencies in both useEffect and useCallback you can use Optional chaining from JS.

const recordProduct = useCallback(() => {
  dispatch(setNextCollectionScroll(router.asPath, hit.handle))
}, [dispatch, hit.handle, router?.asPath])

When router is null, ? will skip trying to get asPath and you will not get a runtime error.

SIDENOTE
In my opinion you should always use a specific property in an object that you are depending on, especially if you are using a third-party library, as it may happen that they return same object reference with a different value (this should be labeled as badly written library, but just in case depend on properties).

It is easier to follow the flow of data and why a particular dependency hook fires.

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