Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jaywcjlove opened this issue Jun 29, 2022 · 0 comments

Comments

@jaywcjlove
Copy link
Member

jaywcjlove commented Jun 29, 2022

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} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant