javascript / expert
Snippet
Recursive Tree Rendering with Memoized Context Resolution
Recursive components are essential for hierarchical data. Using React.memo ensures that only the toggled branch re-renders, preventing expensive full-tree updates in deep structures.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface TreeNodeProps { node: { id: string; label: string; children?: any[] } }const TreeNode = React.memo(({ node }: TreeNodeProps) => {const [isOpen, setIsOpen] = useState(false);return (<div className="tree-node"><div onClick={() => setIsOpen(!isOpen)}>{node.label}</div>{isOpen && node.children && (<div className="children">{node.children.map((child) => (<TreeNode key={child.id} node={child} />))}</div>)}</div>);});
react
Breakdown
1
const TreeNode = React.memo(...)
Prevents re-rendering of sibling branches when a specific node's internal state changes.
2
<TreeNode key={child.id} node={child} />
The component calls itself to render nested levels of the data structure dynamically.