Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda