Skip to content

The code inside useEvent “sees” the props/state values at the time of the call.  #2

@jaywcjlove

Description

@jaywcjlove

https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md

https://codesandbox.io/embed/react-context-example-df8zoq?fontsize=14&hidenavigation=1&theme=dark

Polyfill

function useEvent(fn, dependencies) {
  const ref = useRef(() => {
    throw new Error("Cannot call an event handler while rendering.");
  });

  useEffect(() => {
    ref.current = fn;
  }, [fn, ...dependencies]);

  return useCallback(
    (evn) => {
      const fn = ref.current;
      return fn(evn);
    },
    [ref]
  );
}
function Chat() {
  const [text, setText] = useState('');

  // ✅ Always the same function (even if `text` changes)
  const onClick = useEvent(() => {
    sendMessage(text);
  });

  return <SendButton onClick={onClick} />;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions