Skip to content

Instantly share code, notes, and snippets.

@1natsu172
Created March 14, 2019 08:33
Show Gist options
  • Save 1natsu172/b13f07d3ba5c9c6542ffabb87191c33c to your computer and use it in GitHub Desktop.
Save 1natsu172/b13f07d3ba5c9c6542ffabb87191c33c to your computer and use it in GitHub Desktop.
custom hooks for event handler.
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
)
@1natsu172
Copy link
Author

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 of useLayoutEffect for those who need it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment