In React, side effects can be handled in functional components using useEffect
hook. In this post, I'm going to talk about the dependency array which holds our props/state and specifically what happens in case there's an object in this array.
The useEffect
hook runs even if one element in the dependency array has changed. React does this for optimization purposes. On the other hand, if you pass an empty array then it never re-runs.
However, things become complicated if an object is present in this array. Then even if the object is modified, the hook won't re-run because it doesn't do the deep object comparison between these dependency changes for the object. There are couple of ways to solve this problem.
-
Use lodash's
isEqual
method andusePrevious
hook. This hook internally uses a ref object that holds a mutablecurrent
property that can hold values.It’s possible that in the future React will provide a usePrevious Hook out of the box since it’s relatively common use case.
const prevDeeplyNestedObject = usePrevious(deeplyNestedObject) useEffect(()=>{ if ( !_.isEqual( prevDeeplyNestedObject, deeplyNestedObject, ) ) { // ...execute your code } },[deeplyNestedObject, prevDeeplyNestedObject])
-
Use
useDeepCompareEffect
hook as a drop-in replacement foruseEffect
hook for objects
import useDeepCompareEffect from 'use-deep-compare-effect' ... useDeepCompareEffect(()=>{ // ...execute your code }, [deeplyNestedObject])
Use
useCustomCompareEffect
hook which is similar to solution #2
I've prepared a CodeSandbox example related to this post. Fork it and check it yourself.
Top comments (1)
This is something I have implemented which works very well so far.