React useHover Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the implementation of a custom hook called useHover in React. This hook will handle the event of hovering over a wrapped component and update the state accordingly. By the end of this lab, you will have a better understanding of how to create and use custom hooks in React to enhance the functionality of your components.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38388{{"`React useHover Hook`"}} react/conditional_render -.-> lab-38388{{"`React useHover Hook`"}} react/hooks -.-> lab-38388{{"`React useHover Hook`"}} react/use_state_reducer -.-> lab-38388{{"`React useHover Hook`"}} end

React useHover Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This code creates a custom hook that handles hovering over a wrapped component.

To use the hook:

  • Use useState() to create a variable that holds the hovering state.
  • Use useCallback() to memoize two handler functions that update the state.
  • Use useCallback() to create a callback ref and create or update the listeners for the 'mouseover' and 'mouseout' events.
  • Use useRef() to keep track of the last node passed to callbackRef to be able to remove its listeners.
const useHover = () => {
  const [isHovering, setIsHovering] = React.useState(false);
  const handleMouseOver = React.useCallback(() => setIsHovering(true), []);
  const handleMouseOut = React.useCallback(() => setIsHovering(false), []);
  const nodeRef = React.useRef();
  const callbackRef = React.useCallback(
    (node) => {
      if (nodeRef.current) {
        nodeRef.current.removeEventListener("mouseover", handleMouseOver);
        nodeRef.current.removeEventListener("mouseout", handleMouseOut);
      }
      nodeRef.current = node;
      if (nodeRef.current) {
        nodeRef.current.addEventListener("mouseover", handleMouseOver);
        nodeRef.current.addEventListener("mouseout", handleMouseOut);
      }
    },
    [handleMouseOver, handleMouseOut]
  );

  return [callbackRef, isHovering];
};

This is an example usage of the hook:

const MyApp = () => {
  const [hoverRef, isHovering] = useHover();
  return <div ref={hoverRef}>{isHovering ? "Hovering" : "Not hovering"}</div>;
};

ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useHover Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like