Combining useRef and useMemo for Diffing Nested Objects in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const MyComponent = () => { | |
| const [state, setState] = useState(initialState); | |
| const prevState = useRef(); | |
| // Store the previous state | |
| useEffect(() => { | |
| prevState.current = state; | |
| }, [state]); | |
| // Perform diffing with useMemo | |
| const diff = useMemo(() => { | |
| return deepDiff(prevState.current, state); | |
| }, [state]); | |
| // ... rest of the component | |
| }; |