Created
October 11, 2019 10:00
-
-
Save freddi301/90cdffc898d063df3a4da90b472fcaf5 to your computer and use it in GitHub Desktop.
useReferentialCallback: do not rerender on callback intance change #react #hook
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
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