Home > Software design >  How should we pass event handlers to custom hooks without useEvent?
How should we pass event handlers to custom hooks without useEvent?

Time:10-14

I'm reading through the new docs and I've come across this section on Passing event handlers to custom Hooks which explains an issue of rerenders.

Adding a dependency on onReceiveMessage is not ideal because it will cause the chat to re-connect every time the component re-renders. Wrap this event handler into an Event function to remove it from the dependencies.

This makes sense, but the solution proposes useEvent which has now been dropped.

Question: what is the current convention for dealing with this? Do we just have to wrap the event in useCallback from the component?

CodePudding user response:

Do we just have to wrap the event in useCallback from the component?

Yes. Memoize onReceiveMessage so that it doesn't get re-created unless absolutely necessary. For example, instead of

export default function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');

  useChatRoom({
    roomId: roomId,
    serverUrl: serverUrl,
    onReceiveMessage(msg) {
      showNotification('New message: '   msg);
    }
  });
  // ...

do

export default function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');
  const onReceiveMessage = useCallback((msg) => {
    showNotification('New message: '   msg);
  }, [showNotification]);
  useChatRoom({
    roomId,
    serverUrl,
    onReceiveMessage
  });
  // ...

where showNotification is also made to be as stable a reference as possible (if it's something that comes from React state/props).

  • Related