Created
August 30, 2023 14:30
-
-
Save childrentime/26337155183ab2461bcb55aeb91bdfe8 to your computer and use it in GitHub Desktop.
react useSyncExternalStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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