Skip to content

Commit

Permalink
feat: add useStableCallback
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Apr 26, 2023
1 parent c569716 commit d7aed44
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion packages/utils-react/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,29 @@ export function usePrevious<T>(value: T): T {
return ref.current;
}

// cf. https://github.com/facebook/react/issues/14099#issuecomment-440013892
export function useStableRef<T>(value: T) {
const ref = React.useRef(value);
ref.current = value;

// silence SSR useLayoutEffect warning until https://github.com/facebook/react/pull/26395
const useEffect =
typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;

useEffect(() => {
ref.current = value;
});

return ref;
}

export function useStableCallback<F extends (...args: any[]) => any>(
callback: F
): F {
const ref = useStableRef(callback);
const wrapper = ((...args: any[]) => ref.current(...args)) as F;
return React.useCallback(wrapper, []);
}

export function useRerender() {
return React.useReducer((prev) => !prev, false)[1];
}

0 comments on commit d7aed44

Please sign in to comment.