Collapsible Nested Menu with ARIA Support
Trees & GraphsModel answerLast updated
Design and code a React component that displays hierarchical data with interactive expand/collapse behavior and full keyboard accessibility.
Hierarchical Menu Component
Your task is to build a Tree component in React that displays hierarchical information. Users should be able to expand and collapse branches of the tree independently.
Component Requirements
Data Format
The component receives an array of node objects. Each node contains:
id(string): unique identifierlabel(string): display textchildren(array, optional): nested nodes following the same structure
Example:
[
{
"id": "root-1",
"label": "Documents",
"children": [
{ "id": "node-2", "label": "README.md" },
{
"id": "node-3",
"label": "src",
"children": [
{ "id": "node-4", "label": "index.js" }
]
}
]
}
]
Functional Behavior
- Nodes with children should display a toggle control
- Clicking the toggle expands or collapses that node's children
- Each node's expansion state is independent
- Leaf nodes (no children) should not show a toggle
Accessibility Standards
- Use appropriate ARIA roles:
role="tree"for the container,role="treeitem"for each node - Include
aria-expandedon expandable nodes to indicate current state - Ensure toggle controls are keyboard accessible (Space and Enter keys)
- Use semantic HTML elements (prefer
<button>for interactive controls)
Performance
- Use stable React keys derived from node IDs to prevent unnecessary reconciliation
- Avoid re-rendering unaffected nodes when toggling one branch
Expected Usage
<Tree data={treeData} />
Edge Cases to Handle
- Empty array or
nulldata - Nodes without children
- Deeply nested structures (10+ levels)
- Rapidly toggling the same node
Hints
Hint 1
Consider where expansion state should live—local component state or a shared store?
Hint 2
Recursive components naturally mirror recursive data structures.
Hint 3
useSyncExternalStore can optimize subscriptions to specific slices of state.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires three architectural decisions: how to render the hierarchy, where to store expansion state, and how to meet accessibility requirements.
Rendering Strategy
Use a recursive TreeNode component. Each node renders itself and, when expanded, recursively renders its children in a nested list. This mirrors the data structure naturally. Use the node's id as the React key prop—never use array indices, because indices change when siblings are reordered or filtered, causing React to destroy and recreate components unnecessarily.
State Management
The naive approach stores expansion state locally in each TreeNode with useState. This works but has downsides: state is lost when a parent collapses (unmounting descendants), and there's no easy way to implement "collapse all" functionality.
A better approach: maintain a centralized map of { [nodeId]: boolean } at the tree root. However, passing this map down as props causes a re-render of every mounted node whenever any node toggles, because the entire map object changes.
The optimal solution uses an external store pattern with selective subscriptions. Create a lightweight store holding the expansion map and a set of listener callbacks. Expose it via React context. Each TreeNode subscribes only to its own ID using useSyncExternalStore, which compares snapshots with Object.is. When you toggle node "A", only node "A" sees a changed snapshot and re-renders; siblings and ancestors see identical boolean values and skip rendering.
Accessibility Implementation
- Wrap the top-level list in
<ul role="tree"> - Each
<li>getsrole="treeitem"andaria-level={depth} - Only expandable nodes receive
aria-expanded. Its presence signals to screen readers that the item can expand; omitting it on leaves indicates they're terminal - Use
<button>for toggles—native buttons are focusable and respond to both Enter and Space without custom key handlers - Group children in a nested list with
role="group"andaria-labelledbypointing to the parent label
Code
import React, {
createContext,
useContext,
useState,
useSyncExternalStore,
memo,
} from "react";
function createExpansionStore() {
let state = {};
const listeners = new Set();
return {
getSnapshot: (id) => Boolean(state[id]),
toggle: (id) => {
state = { ...state, [id]: !state[id] };
listeners.forEach((fn) => fn());
},
subscribe: (callback) => {
listeners.add(callback);
return () => listeners.delete(callback);
},
};
}
const StoreContext = createContext(null);
function useNodeExpanded(id) {
const store = useContext(StoreContext);
return useSyncExternalStore(
store.subscribe,
() => store.getSnapshot(id)
);
}
const TreeNode = memo(({ node, depth }) => {
const store = useContext(StoreContext);
const isExpanded = useNodeExpanded(node.id);
const hasChildren = node.children?.length > 0;
return (
<li role="treeitem" aria-expanded={hasChildren ? isExpanded : undefined} aria-level={depth}>
<div>
{hasChildren ? (
<button onClick={() => store.toggle(node.id)} aria-label="Toggle">
{isExpanded ? "−" : "+"}
</button>
) : (
<span style={{ width: "1.5em", display: "inline-block" }} />
)}
<span>{node.label}</span>
</div>
{hasChildren && isExpanded && (
<ul role="group">
{node.children.map((child) => (
<TreeNode key={child.id} node={child} depth={depth + 1} />
))}
</ul>
)}
</li>
);
});
export function Tree({ data = [] }) {
const [store] = useState(createExpansionStore);
if (!data.length) {
return <p>No data available</p>;
}
return (
<StoreContext.Provider value={store}>
<ul role="tree">
{data.map((node) => (
<TreeNode key={node.id} node={node} depth={1} />
))}
</ul>
</StoreContext.Provider>
);
}
Why This Works
Correctness: Each node's expanded state is independent because each subscribes to a distinct ID. The store survives component unmounts, so reopening a collapsed ancestor restores descendant states.
Performance: Only the toggled node re-renders. useSyncExternalStore compares old and new snapshots per subscriber; only the one returning a different boolean triggers a re-render. Memoization and stable keys prevent sibling updates.
Accessibility: Screen readers announce the tree structure, current expansion state, and depth. Keyboard users can tab to buttons and activate with standard keys.
Complexity
- Time: O(V) to render V visible nodes initially. O(1) toggle logic plus O(S) snapshot comparisons across S subscribers, but only one component actually re-renders.
- Space: O(E) for the expansion map (E = expanded nodes), O(V) for mounted components.
Common Mistakes
- Using
<div onClick>instead of<button>—breaks keyboard access - Placing
aria-expandedon leaf nodes—confuses screen readers - Storing state in each node with
useState—loses state on unmount - Passing the entire expansion map as props—causes cascading re-renders
- Using array indices as keys—breaks React reconciliation
Follow-Up: Large Trees
For thousands of nodes, virtualize the display. Flatten visible nodes into an array using an iterative depth-first traversal that only descends into expanded branches. Render the viewport window with react-window or @tanstack/virtual. Since the DOM is no longer nested, you must supply aria-level, aria-posinset, and aria-setsize explicitly to maintain semantic structure for assistive technologies.