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]
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.