useSyncExternalStoreExports in Zustand source code explained.
In this article, we will look at how Zustand uses useSyncExternalStoreExports
in its source code.
useSyncExternalStoreExports
is imported from use-sync-external-store/shim/with-selector. use-sync-external-store is a backwards-compatible shim for React.useSyncExternalStore
Works with any React that supports Hooks.
Reading the above sentence, you might be wondering what a useSyncExternalStore.
useSyncExternalStore
useSyncExternalStore
is a React Hook that lets you subscribe to an external store.
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)
Use the useSyncExternalStore to read a value from external store that can be:
-
Third-party state management libraries that hold state outside of React.
-
Browser APIs that expose a mutable value and events to subscribe to its changes.
Example usage:
import { useSyncExternalStore } from 'react';
import { todosStore } from './todoStore.js';
function TodosApp() {
const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot);
// ...
}
The above example is picked from React docs.
useSyncExternalStore Usage In Zustand:
Zustand uses useSyncExternalStore
in src/traditional.ts.
import ReactExports from 'react'
// eslint-disable-next-line import/extensions
import useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector'
import { createStore } from './vanilla.ts'
import type {
Mutate,
StateCreator,
StoreApi,
StoreMutatorIdentifier,
} from './vanilla.ts'
const { useDebugValue } = ReactExports
const { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports
useSyncExternalStoreWithSelector
is de-structured from useSyncExternalStoreExports
and this is used in useStoreWithEqualityFn
.
export function useStoreWithEqualityFn<TState, StateSlice>(
api: ReadonlyStoreApi<TState>,
selector: (state: TState) => StateSlice = identity as any,
equalityFn?: (a: StateSlice, b: StateSlice) => boolean,
) {
const slice = useSyncExternalStoreWithSelector(
api.subscribe,
api.getState,
api.getInitialState,
selector,
equalityFn,
)
useDebugValue(slice)
return slice
}
useSyncExternalStoreWithSelector has api.subscribe, api.getState, api.getInitialState, selector and equalityFn.
About us:
At Think Throo, we are on a mission to teach the best practices inspired by open-source projects.
10x your coding skills by practising advanced architectural concepts in Next.js/React, learn the best practices and build production-grade projects.
We are open source — https://github.com/thinkthroo/thinkthroo (Do give us a star!)
Up skill your team with our advanced courses based on codebase architecture. Reach out to us at hello@thinkthroo.com to learn more!