Skip to content

Instantly share code, notes, and snippets.

@giladv
giladv / useEvent.tsx
Created November 15, 2021 14:57
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) {