Skip to content

Instantly share code, notes, and snippets.

@btoo
Last active March 26, 2024 04:33
Show Gist options
  • Save btoo/ae5dfcb1ccebf5496352365d1f1434a1 to your computer and use it in GitHub Desktop.
Save btoo/ae5dfcb1ccebf5496352365d1f1434a1 to your computer and use it in GitHub Desktop.
typescript type-safe version of the approximate implementation of react's (no longer) proposed useEvent hook
import { useCallback, useLayoutEffect, useRef } from 'react';
/** typescript type-safe version of [the approximate implementation of react's (no longer) proposed `useEvent` hook](https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#internal-implementation) */
export function useEvent<Args extends Array<unknown>, Return>(
handler: (...args: Args) => Return,
): typeof handler {
const handlerRef = useRef(handler);
useLayoutEffect(() => {
handlerRef.current = handler;
});
return useCallback((...args) => handlerRef.current(...args), []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment