Child Component Updates Based on Specific Nested Value Changes
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
| // Parent Component | |
| const ParentComponent = () => { | |
| const [node, setNode] = useState({ nodeValue: 'initial', otherProp: 'other' }); | |
| // ... code to update node | |
| return <ChildComponent node={node} />; | |
| }; | |
| // Child Component | |
| const ChildComponent = ({ node }) => { | |
| const [nodeValue, setNodeValue] = useState(node.nodeValue); | |
| // Memoize nodeValue to prevent unnecessary calculations | |
| const memoizedNodeValue = useMemo(() => node.nodeValue, [node.nodeValue]); | |
| // Update nodeValue state only when node.nodeValue changes | |
| useEffect(() => { | |
| setNodeValue(memoizedNodeValue); | |
| }, [memoizedNodeValue]); | |
| return <div>{nodeValue}</div>; | |
| }; |