Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 10:00
Show Gist options
  • Save freddi301/90cdffc898d063df3a4da90b472fcaf5 to your computer and use it in GitHub Desktop.
Save freddi301/90cdffc898d063df3a4da90b472fcaf5 to your computer and use it in GitHub Desktop.
useReferentialCallback: do not rerender on callback intance change #react #hook
import React from "react";
export function useReferentialCallback<F extends (...args: any[]) => any>(
fn: F,
deps?: any[],
): F {
const fnRef = React.useRef<F>(fn);
React.useLayoutEffect(() => {
fnRef.current = fn;
}, deps); // eslint-disable-line
return React.useCallback(
((...args: any) => {
fnRef.current(...args);
}) as any,
[],
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment