Advanced ReactJS lesson 1: Create the first hooks (useHover)

Tram Ho

Hello friends!

In this series, I will start sharing what can be called advanced Reactjs knowledge, as it is not for those new to Reactjs. I will try to explain as much as possible the meaning of each piece of code written. I hope my sharing will be useful to all of you who are using Reactjs. If you discover errors in your posts, please comment below for me! Thank you!

Let’s get started!

Problem: In React components, we often use the Hover mouse over component handler events very often. In the usual way we would write something like this:

It doesn’t matter if your app has only a few components that must use mouse Hover events. But what if your App has too much room to use it? Should I rewrite this pile in every component? The obvious answer is no, one way or another, but you’ll definitely have to repack them for reuse. Higer Order Component can be thought of as a solution.

Here, I will provide a solution to handle it for reuse in the simplest way. That is: Creates a hooks to handle the mouse Hover event. The result will be a function useHover() and we can use it easily as follows:

Live demo:

Watch live Demo on Codesanbox

Really simple, right? now when we need to trigger Hover on a certain component, we just need a few simple lines to finish.

And now it’s the code!

Code explanation

Go back to the code used above:

We see that the function useHover() returns an object containing 2 parameters: hoverProps is the function that handles Hover events to insert into your component; isHovered is the boolean value, true when hovering the mouse over the element. You can also further handle hover events by passing the props of the useHover() function:

Details in useHover () function probably do not need any further explanation because it is very clean already, right? If you find something difficult to understand, do not hesitate to comment below! I will answer as soon as possible!

End of the first post here. Hope this article is useful to you. Thank you for taking the time to read my post!

Share the news now

Source : Viblo