I am looking at the code in formik that apparently is a way around the stale closure problem with react hooks.
function useEventCallback<T extends (...args: any[]) => any>(fn: T): T {
const ref: any = React.useRef();
// we copy a ref to the callback scoped to the current state/props on each render
useIsomorphicLayoutEffect(() => {
ref.current = fn;
});
return React.useCallback(
(...args: any[]) => ref.current.apply(void 0, args),
[]
) as T;
}
I've seen this pattern a lot in other libs but I don't understand why this cures it.
I don't understand why creating a ref
in a useEffect()
cures anything.
Does it silence the linter?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…