mediumcodingjavascript~12 min
Build a Subscribable Store
Objective: Understand the snapshot/subscribe contract behind external state libraries.
Implement `createStore(initial)` with `getState`, `setState(updater)` and `subscribe(listener)`: the contract `useSyncExternalStore` expects.
- `setState` accepts a value or a function of the previous state.
- Listeners are notified only when the new state is not `Object.is`-equal to the old one.
- `subscribe` returns an unsubscribe function.
- `getState` returns the same reference until state changes.
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- Why must getSnapshot return a cached value?
- What is tearing and how does useSyncExternalStore prevent it?
- How would you add selectors without re-rendering on unrelated changes?