Created
February 7, 2023 06:42
-
-
Save chhornponleu/6b43f4d90b24dc2e8067a17e4d0b86ac to your computer and use it in GitHub Desktop.
useEffectEvent
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
| /** | |
| * original https://github.com/scottrippey/react-use-event-hook | |
| */ | |
| import { useLayoutEffect, useRef } from 'react'; | |
| type AnyFunction = (...args: any[]) => any; | |
| function useEvent_shouldNotBeInvokedBeforeMount() { | |
| console.warn( | |
| 'INVALID_USEEVENT_INVOCATION: the callback from useEvent cannot be invoked before the component has mounted.' | |
| ); | |
| // throw new Error( | |
| // 'INVALID_USEEVENT_INVOCATION: the callback from useEvent cannot be invoked before the component has mounted.' | |
| // ); | |
| } | |
| export function useEffectEvent<TCallback extends AnyFunction>(callback: TCallback): TCallback { | |
| // Keep track of the latest callback: | |
| const latestRef = useRef<TCallback>(useEvent_shouldNotBeInvokedBeforeMount as any); | |
| useLayoutEffect(() => { | |
| latestRef.current = callback; | |
| }, [callback]); | |
| const stableRef = useRef<TCallback>(null as any); | |
| if (!stableRef.current) { | |
| stableRef.current = function (...args) { | |
| latestRef.current?.(...args); | |
| } as TCallback; | |
| } | |
| return stableRef.current; | |
| } | |
| export default useEffectEvent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment