All questions

Lazy Tree View

Premium

Lazy Tree View

Build a collapsible file tree in React. Every folder starts closed, and a folder's contents are unknown until you open it — the first click on a folder fetches its children (a short async load), shows a spinner while it waits, then reveals them. This is how real file explorers and API-backed trees stay fast: you only pay to load a branch when someone actually looks inside it.

Task

The starter App.tsx renders the tree in its resting state: four top-level rows, all folders collapsed, the file not expandable. The Node component and CSS are done. Make it interactive:

  1. Hold the tree in state. Lift initialTree into useState and pass an onToggle handler down to each Node; call it when a row is clicked.
  2. Lazily load on first open. When a folder is clicked and its children is null (never opened): set loading, await a loadChildren(node) that resolves 2–3 children after ~500ms, then store the children, set expanded, and clear loading.
  3. Cache after that. If the folder's children are already loaded, just flip expanded — no refetch. Files (type: 'file') never expand.

Update the matching node immutably with a recursive updateNode(nodes, id, patch) helper so React re-renders the changed branch.

Examples

  • Clicking 📁 src swaps the for a spinner, waits ~500ms, then expands to show its children indented beneath it with a .
  • Collapsing src and re-opening it is instant — the children are already in state, so there is no second fetch.
  • Clicking 📄 README.md does nothing: files have no children to load.

Notes

  • children: null means "not loaded yet". That is the flag that distinguishes a first open (fetch) from a cached re-open (toggle).
  • Mutating state won't re-render. Patch the tree immutably via updateNode so the changed branch gets a fresh reference.
  • The spinner, the / twist, and the indentation are pure CSS — you only flip loading, expanded, and children in state.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium