React Custom Hook: Hovering Made Easy with useHover!

Evelyn Taylor
3 min readSep 12, 2023
Photo by Aaron Burden on Unsplash

Hey there, fellow React enthusiasts! Today, we’re diving into the world of custom hooks and learning about one of the most useful ones: useHover.

If you're new to React or just starting your journey, don't worry!

We'll take it step by step and make sure you understand everything with plenty of examples.

What’s a Custom Hook?

First things first, what’s a custom hook? In React, a custom hook is simply a JavaScript function that starts with the word “use” and lets you hook into React state and lifecycle features from functional components.

Think of them as a way to reuse stateful logic across different components.

Custom hooks can be a real lifesaver when you find yourself repeating the same logic in multiple places.

Today, we’re going to create a custom hook called useHover that will help us detect when an element is being hovered over.

The useHover Hook

Here’s a simple use case for our useHover hook: Let's say you have a button, and you want to change its color when a user hovers over it.

We could write this behavior in a custom hook to make it reusable. Here's how you can create the useHover hook:

import { useState, useEffect } from 'react';

function useHover() {
const [isHovered, setIsHovered] = useState(false);

const handleMouseEnter = () => {
setIsHovered(true);
};

const handleMouseLeave = () => {
setIsHovered(false);
};

useEffect(() => {
const element = document.querySelector('.hover-element'); // Replace with your element selector
element.addEventListener('mouseenter', handleMouseEnter);
element.addEventListener('mouseleave', handleMouseLeave);

return () => {
element.removeEventListener('mouseenter', handleMouseEnter);
element.removeEventListener('mouseleave', handleMouseLeave);
};
}, []);

return isHovered;
}

Here’s a breakdown of what’s happening:

  1. We import the necessary React hooks, useState and useEffect.
  2. Inside the useHover function, we initialize a state variable, isHovered, and two event handlers, handleMouseEnter and handleMouseLeave.
  3. We use the useEffect hook to add event listeners for mouseenter and mouseleave events to the specified element (you'll need to replace .hover-element with your own selector). These event listeners will call our event handlers when the mouse enters and leaves the element.
  4. We return the isHovered state variable. This tells us whether the element is currently being hovered over or not.

Using the useHover Hook

Now that we have our useHover hook ready, let's see how we can use it in a functional component:

import React from 'react';
import useHover from './useHover'; // Import our custom hook

function HoverExample() {
const isHovered = useHover();

const buttonColor = isHovered ? 'blue' : 'red';

return (
<button
className="hover-element"
style={{ backgroundColor: buttonColor }}
>
Hover me!
</button>
);
}

export default HoverExample;

Here’s what’s happening in the HoverExample component:

  1. We import our custom hook useHover at the top of the file.
  2. Inside the HoverExample component, we call useHover(), which gives us the isHovered value.
  3. We use the isHovered value to determine the button's background color. If isHovered is true, we set the color to blue; otherwise, it's red.
  4. Finally, we render a button element with the class name hover-element and apply the dynamic background color based on the hover state.

Result:

Wrapping Up

And that’s it! You’ve just created and used your own custom hook, useHover, to add hover functionality to a button.

The beauty of custom hooks is that you can reuse them across different components, making your code more readable and maintainable.

Custom hooks are a powerful tool in your React toolbox. They allow you to abstract away complex logic and provide a clean API for your components.

So, go ahead and create your custom hooks for various use cases, and level up your React development skills.

Happy coding! 😄🚀

Connect with me on Medium ✍ : https://medium.com/@Evelyn.Taylor

--

--

Evelyn Taylor

A front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.