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

130
Views
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 answers
Answer question

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 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!