Skip to content

Instantly share code, notes, and snippets.

@childrentime
Created August 30, 2023 14:30
Show Gist options
  • Save childrentime/26337155183ab2461bcb55aeb91bdfe8 to your computer and use it in GitHub Desktop.
Save childrentime/26337155183ab2461bcb55aeb91bdfe8 to your computer and use it in GitHub Desktop.
react useSyncExternalStore
import { useCallback, useRef, useSyncExternalStore } from "react";
const useThirdPartyStore = () => {
const symbolRef = useRef(Symbol());
const storeChangeRef = useRef<() => void>();
const subscribe = useCallback((storeChange: () => void) => {
storeChangeRef.current = storeChange;
return () => {
storeChangeRef.current = undefined;
};
}, []);
const getSnapshot = useCallback(() => {
return symbolRef.current;
}, []);
useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
/**
* when store change, call this function to rerender
*/
const rerender = useCallback(() => {
storeChangeRef.current?.();
symbolRef.current = Symbol();
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment