Created
March 14, 2019 08:33
-
-
Save 1natsu172/b13f07d3ba5c9c6542ffabb87191c33c to your computer and use it in GitHub Desktop.
custom hooks for event handler.
This file contains 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 { useRef, useCallback, useEffect, useLayoutEffect } from 'react' | |
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
/** | |
* | |
* @description For reference state value on event handler. | |
* @see https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback | |
* @see https://github.com/facebook/react/issues/14099 | |
* @todo `unknown` type loos better than `any`. But can't use unknown……Error message "Type 'unknown' is not assignable to type ~" why?? | |
*/ | |
const useEventCallbackBase = <T extends (...args: any[]) => unknown>( | |
useEffectHook: typeof useEffect | typeof useLayoutEffect, | |
fn: T, | |
deps: ReadonlyArray<unknown> | |
) => { | |
const ref = useRef<T>(fn) | |
useEffectHook(() => { | |
ref.current = fn | |
}, [fn, ...deps]) | |
return useCallback( | |
(...args: any[]) => { | |
const callback = ref.current | |
callback(...args) | |
}, | |
[ref] | |
) | |
} | |
export const useEventCallback = useEventCallbackBase.bind(null, useLayoutEffect) | |
export const useEventCallbackWithUseEffect = useEventCallbackBase.bind( | |
null, | |
useEffect | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related: facebook/react#14099
This gist is escape hatch for event handler in React hooks.
cf. https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
Export two ways to use
useEffect
instead ofuseLayoutEffect
for those who need it.