Skip to content

Instantly share code, notes, and snippets.

@giladv
Created November 15, 2021 14:57
Show Gist options
  • Save giladv/a39b0b29c5b52606e07994b5f3067688 to your computer and use it in GitHub Desktop.
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)
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