Created
November 15, 2021 14:57
-
-
Save giladv/a39b0b29c5b52606e07994b5f3067688 to your computer and use it in GitHub Desktop.
a gist for subscribing for an event as soon as possible. (before useEffect runs)
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
type UnsubscribeFunc = () => void; | |
function useEvent(subscribeFunc: () => UnsubscribeFunc, deps: any[] = []) { | |
// we use ref instead of useMemo because on strict mode useMemo is being called twice | |
const unsubscribeFunc = useRef(subscribeFunc()); | |
useEffect(() => { | |
// this will only be called after a change in deps. | |
// initial subscription happens sooner than useEffect | |
if (!unsubscribeFunc.current) { | |
unsubscribeFunc.current = subscribeFunc(); | |
} | |
return () => { | |
unsubscribeFunc.current(); | |
unsubscribeFunc.current = null; | |
}; | |
}, deps); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment