DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

marvelken
marvelken

Posted on

Introduction to Useevent()

Introduction;

The React team released an RFC (Request For Comments) on May 4th suggesting the release of a new hook called UseEvent ().

There is no denying the excellent quality of react hooks as tools. The best feature about them is that they make it possible to design simple, easy-to-understand functional components with well-defined actions.

UseEvent() is one of the new hooks being actively developed by React since it believes hooks are the future of the framework.

Prerequisite

Readers will need knowledge on how useCallBack(), and useRef() hooks are used in React to handle events.

Goals;

Recently, the useEvent() hook was suggested. In less than 900 words, we'll discuss the issue that the useEvent() hook addresses and provide several examples of how to use it effectively..

Why Was The Hook Proposed

If you are a React developer you might find yourself stuck in one of these situations, where you want your code to react to user events, but because they happen very often you want to optimize them.
If you are creating a chat, for example, you might have your recent message stored in a state that gets updated with every keystroke like this:

function Chat() {
   const [message, setMessage] = useState('')
   const onSend = () => {
       sendMessage(message)
   }

   return (
       <div >
           <input onSend={Send} />
       </div>
   )
}
Enter fullscreen mode Exit fullscreen mode

When the user is ready, they can send their final message through the onSend() function above.
When it comes to optimization, you can wrap onSend with useCallback() to make sure the function only gets recreated when your state changes.

const onSend = useCallback(()=>{
       sendMessage(message)
   }, [message])
Enter fullscreen mode Exit fullscreen mode

Well, this is great, because now input will not re-render unless on onSend gets re-created, but at the same time this optimization is not precisely what we would hope for, because onSend will be re-created every single time your messages change.

message=” common” =Recreated
message=” Common ninja” =Recreated
message=” Common ninja blog” =Recreated

How was this fixed before the useEvent() hook?, The useRef() hook was a saver.

 const send= useRef(null);
 useLayoutEffect(() => {
     send.current=()=>sendMessage(message)
   })
Enter fullscreen mode Exit fullscreen mode

Send here will store our event handler so that onSend will always have the same function you are passing down to input.

const onSend = useCallback((...args)=>{
     return send.current(...args)
   }, [])
Enter fullscreen mode Exit fullscreen mode

Although this works, it comes at a cost of losing a lot in code readability, and here is why the useEvent() React hook came to our rescue.

Refactor code with useEvent()

Use event is very similar to useCallback(), so the implementations look much alike, except for the fact that useEvent() has no dependency array.

If we go back to what we usually write in React applications, the main difference usually lies in the number of re-renders that will happen in the code below:

const onSend = useCallback(()=>{
     sendMessage(message)
   }, [message])
Enter fullscreen mode Exit fullscreen mode

With useCallback() when we create a new function and the message changes, the input will re-render anytime it does.

With useEvent():

const onSend=useEvent(()=>{
     sendMessage(message)
   })
Enter fullscreen mode Exit fullscreen mode

We are only going to trigger one rendering and the component mounts, the reason being that the function onSend will always be the same and that's even the reason why we could drop the dependencies entirely.

In terms of what useEvent() returns, it behaves just like a normal function. So you could also pass in arguments, like RoomID, and call it inside the input, as you normally would ;

const onSend = useEvent((roomID)=>{
       sendMessage(roomID, message)
   })
Enter fullscreen mode Exit fullscreen mode

UseEvent() is very useful for handlers and events and you will always find them a lot with useEffect.

If we go back to our chat example, let's say we want to show a success alert and empty our current message:

function Chat() {
   const [message, setMessage] = useState('')
 const onSend = useEvent((roomID)=>{
       sendMessage(roomID, message)
   })
   return (
       <div >
           <input onSend={onSend} />
       </div>
   )
}



   useEffect(() => {
      showToast('change chat')
      setMessage('')

   }, [roomID])
Enter fullscreen mode Exit fullscreen mode

This would be great, but if our toast reads from our current theme context const Theme= useContext(ThemContext);, we will need our effect to add it as a dependency,like this:

useEffect(() => {
      showToast(theme, 'change chat')
      setMessage('')

   }, [roomID, theme])
Enter fullscreen mode Exit fullscreen mode

and the code above will break it.

We just don't want our toast to appear whenever our theme changes, but then this could be taken outside the effect and converted to a callback():

 const Theme= useContext(ThemContext);



  const onChangeRoom =useCallback(()=>{
       showToast(theme, 'change chatroom')
       setMessage("")
   },[theme])

   useEffect(() => {
    onChangeRoom()

   }, [roomID])
Enter fullscreen mode Exit fullscreen mode

Remember we said useEvent() prevents re-renders so basically it will make more sense here if the function is passed down to a component.

 const onChangeRoom= useEvent(()=>{
showToast(theme, 'change chatroom')
setMessage("")
})
Enter fullscreen mode Exit fullscreen mode




Conclusion

We were able to discuss the few questions React raises and useEvent() answers, which raises high prospects for improved readability. UseEvent() is an outstanding hook because it will handles events flawlessly.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.