Skip to content

Instantly share code, notes, and snippets.

@ambroseus
Last active January 2, 2024 09:47
Show Gist options
  • Save ambroseus/c729dcf2e4f5853c27d0c1ee185e3704 to your computer and use it in GitHub Desktop.
Save ambroseus/c729dcf2e4f5853c27d0c1ee185e3704 to your computer and use it in GitHub Desktop.

Revisions

  1. ambroseus revised this gist Jan 2, 2024. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion useEvent.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,4 @@
    // A Hook to define an event handler with an always-stable function identity
    // https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md

    function useEvent(handler) {
    const handlerRef = useRef(null);
  2. ambroseus revised this gist Jan 2, 2024. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions useEvent.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    // A Hook to define an event handler with an always-stable function identity
    // https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md

    function useEvent(handler) {
  3. ambroseus renamed this gist Jan 2, 2024. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. ambroseus created this gist Jan 2, 2024.
    16 changes: 16 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    // https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md

    function useEvent(handler) {
    const handlerRef = useRef(null);

    // In a real implementation, this would run before layout effects
    useLayoutEffect(() => {
    handlerRef.current = handler;
    });

    return useCallback((...args) => {
    // In a real implementation, this would throw if called during render
    const fn = handlerRef.current;
    return fn(...args);
    }, []);
    }