A Hook to define an event handler with an always-stable function identity.
The above line is from the description of the useEvent hook in the rfc released by React team - https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
React team recently announced they are working on a new hook called useEvent, I am fascinated by the use case it solves in our application code -
1) to prevent unnecessary re-render of child components even though the function uses the latest values from the parent component. example -
in this code, on every user input change, the ChildComponent will re-render,this can easily be prevented with a useCallback with dependencies on text, but that would not be useful as in dependencies, we will use text, and it will still cause the child to re-render on every input change, here comes our saviour useEffect, so if we wrap the sendMessage function with this hook, the child won't re-render, and when called on click it will consume the latest state of text in the parent too, this is really useful as it removes the pain of finding the right dependencies to be added in the useCallback to improve optimisation, let's see what have we changed with useEvent -
2) is not a replacement of useCallback hook
The main difference I see between useEvent and useCallback is if the functions need to be called in child with the latest data at a later stage on change of event, we should use useEvent(whenever it is available in react offical release) otherwise when we want component's UI to be updated(or show calculated UI data) on change of a state in parent we should use useCallback.
The useEvent can solve the issue of revalidating too much of the useCallback but it doesn't solve every usecase and is discussed more on the rfc too.
But in the meanwhile, I wrote this article. In the current version of React, the useEvent hook is not available. So keep your eyes peeled for another update! Thank you for reading. I hope you like it. 👋🏼
Top comments (0)