The Set object lets you store unique values of any type, whether primitive values or object references. Set objects are collections of values. A value in the set may only occur once; it is unique in the set's collection. You can iterate through the elements of a set in insertion order. — MDN Docs
How is subscribe used in a React project? the below explanation is picked from Zustand’s Readme.
The subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a drastic performance impact when you are allowed to mutate the view directly.
const useScratchStore = create((set) => ({ scratches: 0, ... }))const Component = () => { // Fetch initial state const scratchRef = useRef(useScratchStore.getState().scratches) // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference useEffect(() => useScratchStore.subscribe( state => (scratchRef.current = state.scratches) ), []) ...
Let’s now look at the subscribe source code in Zustand.
subscribe simply adds the listener to the listeners Set.
Let’s see what the logs from experimentation say. To add the console.log statements, I compiled Zustand using the command pnpm run build and copied the dist into examples/demo/src. Looks hacky, but hey we are experimenting and figuring out how Zustand works internally.
This is how the listeners Set looks like
I subscribed to changes in App.jsx
// Subscribe to changes in the stateuseStore.subscribe((state) => { console.log("State changed: ", state);});
Another observation is that, there is a additional listener that got added to this set:
ƒ () { if (checkIfSnapshotChanged(inst)) { forceStoreRerender(fiber); }}
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.