useSyncExternalStore API and Parameters
Learn the subscribe, getSnapshot, and getServerSnapshot arguments and what they must guarantee.
Three Arguments Overview
useSyncExternalStore takes up to three arguments: subscribe, getSnapshot, and an optional getServerSnapshot. Together they tell React how to listen for changes and how to read the current value.
Understanding each argument is essential, since small mistakes in them are the most common source of bugs when using this hook.
The subscribe Function
subscribe receives a callback from React and must register it with the store so the callback runs whenever the store changes. It must return an unsubscribe function that React calls on cleanup.
React uses this to know when to re-read the snapshot, so subscribe is purely about wiring up and tearing down the change notification.
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