DEV Community

vsr
vsr

Posted on • Updated on

Ways to Handle Deep Object Comparison in useEffect hook

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)
    useEffect(()=>{
        if (
            !_.isEqual(
                prevDeeplyNestedObject,
                deeplyNestedObject,
            )
        ) {
            // ...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'
    ...
    useDeepCompareEffect(()=>{
        // ...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.

Top comments (1)

Collapse
 
peculiarity profile image
John Doe

This is something I have implemented which works very well so far.

import { isEqual } from 'lodash'
import { useRef } from 'react'

export function useDeepEqualMemo<T>(value: T) {
  const ref = useRef<T | undefined>(undefined)

  if (!isEqual(ref.current, value)) {
    ref.current = value
  }

  return ref.current
}
Enter fullscreen mode Exit fullscreen mode