|
| 1 | +# `useDeepCompareEffect` |
| 2 | + |
| 3 | +A hook for running an effect with dependencies that are deeply compared. |
| 4 | + |
| 5 | +## Arguments |
| 6 | + |
| 7 | +- `callback` (`function`): The effect function to run. |
| 8 | +- `dependencies` (`array`): The dependencies for the effect, deeply compared. |
| 9 | + |
| 10 | +## Returns |
| 11 | + |
| 12 | +- None |
| 13 | + |
| 14 | +## Hooks Involved |
| 15 | + |
| 16 | +- [useEffect](https://react.dev/reference/react/useEffect) |
| 17 | +- [useRef](https://react.dev/reference/react/useRef) |
| 18 | + |
| 19 | +## libraries Involved |
| 20 | +- isEqual `lodash --> lodash/fp/isEqual` |
| 21 | + |
| 22 | +## How to Use |
| 23 | + |
| 24 | +```js |
| 25 | +import { useEffect, useState, useRef } from "react" |
| 26 | +import useDeepCompareEffect from "./useDeepCompareEffect" |
| 27 | + |
| 28 | +export default function DeepCompareEffectComponent() { |
| 29 | + const [age, setAge] = useState(0) |
| 30 | + const [otherCount, setOtherCount] = useState(0) |
| 31 | + const useEffectCountRef = useRef() |
| 32 | + const useDeepCompareEffectCountRef = useRef() |
| 33 | + |
| 34 | + const person = { age: age, name: "Sergey" } |
| 35 | + |
| 36 | + useEffect(() => { |
| 37 | + useEffectCountRef.current.textContent = |
| 38 | + parseInt(useEffectCountRef.current.textContent) + 1 |
| 39 | + }, [person]) |
| 40 | + |
| 41 | + useDeepCompareEffect(() => { |
| 42 | + useDeepCompareEffectCountRef.current.textContent = |
| 43 | + parseInt(useDeepCompareEffectCountRef.current.textContent) + 1 |
| 44 | + }, [person]) |
| 45 | + |
| 46 | + return ( |
| 47 | + <div> |
| 48 | + <div> |
| 49 | + useEffect: <span ref={useEffectCountRef}>0</span> |
| 50 | + </div> |
| 51 | + <div> |
| 52 | + useDeepCompareEffect: <span ref={useDeepCompareEffectCountRef}>0</span> |
| 53 | + </div> |
| 54 | + <div>Other Count: {otherCount}</div> |
| 55 | + <div>{JSON.stringify(person)}</div> |
| 56 | + <button onClick={() => setAge(currentAge => currentAge + 1)}> |
| 57 | + Increment Age |
| 58 | + </button> |
| 59 | + <button onClick={() => setOtherCount(count => count + 1)}> |
| 60 | + Increment Other Count |
| 61 | + </button> |
| 62 | + </div> |
| 63 | + ) |
| 64 | +} |
| 65 | +``` |
0 commit comments