Syncing State with localStorage
Build a useLocalStorage custom hook that keeps React state and localStorage in sync bidirectionally.
The Naive Approach Gets Out of Sync
A first instinct is to read localStorage in one place and write it in another, but these can drift apart. State updates that forget to persist, or persisted values not reflected in state, lead to bugs.
You want a single source of truth that keeps React state and storage in lockstep.
The useLocalStorage Custom Hook
The clean solution is a useLocalStorage hook that wraps useState and persists changes automatically. It returns a value and setter just like useState.
Consumers use it exactly like normal state but get persistence for free.