useDeepCompareEffect
About
A React hook that works like useEffect
but performs deep comparison on dependencies instead of shallow comparison. This is useful when you have object or array dependencies that may have the same content but different references, preventing unnecessary re-renders and effect executions.
Examples
Basic example with object dependencies
Example with array dependencies
Example with cleanup function
Arguments
Argument value | Type | Description | Default |
---|---|---|---|
callback | EffectCallback | The effect function to run when dependencies change | - |
dependencies | DependencyList | An array of dependencies to deep compare | - |
Returns
This hook returns void
. It doesn't return any value, but executes the provided callback when dependencies change based on deep comparison.
Important Notes
- Performance: Deep comparison is more expensive than shallow comparison. Use this hook only when you actually need deep comparison of object/array dependencies.
- Primitive Values Warning: The hook will warn you in development mode if you use it with only primitive values (string, number, boolean, etc.), since regular
useEffect
would be more efficient. - Array Required: Dependencies must be provided as an array. The hook will throw an error if dependencies are not an array.
- Cleanup Support: Like
useEffect
, you can return a cleanup function from your effect callback that will be called before the effect runs again or when the component unmounts.
When to Use
Use useDeepCompareEffect
when:
- You have object or array dependencies that may have the same content but different references
- You want to prevent unnecessary effect executions due to reference changes
- You're dealing with complex data structures in your dependencies
Avoid using it when:
- All your dependencies are primitive values (use regular
useEffect
instead) - Performance is critical and you can restructure your code to avoid deep comparison
- You can use
useCallback
oruseMemo
to stabilize object references instead