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} />;
}