Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How should we pass event handlers to custom hooks without useEvent?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading