Building a Custom Store with useSyncExternalStore
Implement a lightweight external store from scratch and connect it to React with useSyncExternalStore.
Minimal Store Requirements
A custom store needs three things: some state, a subscribe method to register listeners, and a getSnapshot method to read the current state. That is the full contract useSyncExternalStore expects.
Keeping the store this small makes it framework-agnostic, so the same store can be used inside or outside React.
A createStore Factory
A createStore factory takes an initial value and returns an object with getSnapshot, subscribe, and an update method. Internally it holds the current state and a set of listener callbacks.
This factory pattern lets you spin up multiple independent stores with a single reusable function.
All lessons in this course
- The Problem with External Store Subscriptions
- useSyncExternalStore API and Parameters
- Subscribing to Browser APIs
- Building a Custom Store with useSyncExternalStore