Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 27.3 — State, Reducer and Persistence
React · Example 3 of 3 React 18+

A persistent store: save, reload, survive broken data

The same store works for any reducer. Code outside React (here the script at the bottom) can dispatch and read it, and React stays in step.

Milestones 2 and 3: every change to the tasks goes through one reducer, the tasks and dispatch are shared by two contexts with custom hooks, and a small external store read with useSyncExternalStore saves them to localStorage so they survive a reload.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Add a "cleared-done" action to tasksReducer and show the full case.

02

Write a useTaskCount(status) custom hook that returns how many tasks have that status.

Explain it without notes

01

Why split the tasks and dispatch into two contexts?

02

How does useSyncExternalStore work, and why must getSnapshot return a cached value?

03

Compare saving tasks with useReducer + useEffect against an external store.

04

How would you keep two open tabs of the board in sync?

A persistent store: save, reload, survive broken data React 18+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

in storage: 2
after reload: 41
bad saved data, using the fallback
after a broken value: 0
button says: Saved count: 0