DEV Community


Ways to Handle Deep Object Comparison in useEffect hook

w1n5rx profile image Vinod Singh Ramalwan Updated on ・2 min read

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.

  1. Use lodash's isEqual method and usePrevious hook. This hook internally uses a ref object that holds a mutable current 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)
        if (
        ) {
            // ...execute your code
    },[deeplyNestedObject, prevDeeplyNestedObject])
  2. Use useDeepCompareEffect hook as a drop-in replacement for useEffect hook for objects

    import useDeepCompareEffect from 'use-deep-compare-effect'
        // ...execute your code
    }, [deeplyNestedObject])
  3. 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.


Editor guide