1

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]

Xin
  • 33,823
  • 14
  • 84
  • 85
  • Maybe you should check if `router.asPath` is not undefined before calling `dispatch()`? – Terry Jan 15 '22 at 23:35

1 Answers1

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.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • This did work. Actually router will not be null in prod, but only has issue in unit tests, where router is null, but I do not want mock as router null should also pass the test. This should keep code clean as well as keep the performance. – Xin Jan 16 '22 at 08:20