How do you subscribe to an external store safely?

React hooks and effects · Experienced

Model answer

Use useSyncExternalStore. You pass a subscribe function and a function that returns the current snapshot, and React keeps the component consistent with the store, including during concurrent rendering and server rendering.

State libraries such as Redux and Zustand use it internally. Writing the same thing with useEffect and useState can cause tearing, where parts of the UI show different values.

Learn this topic

React useEffect Explained: Side Effects, Dependencies and Cleanup in the course React.js Full Course: Beginner to Advanced.

Sign in to add your own answer.

More questions