開源日報每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,堅持閱讀《開源日報》,保持每日學習的好習慣。

2024年1月16日,開源日報第1076期:
今日推薦開源項目:《danswer》
今日推薦英文原文:《React Custom Hook: Hovering Made Easy with useHover》


開源項目

今日推薦開源項目:《danswer》傳送門:項目鏈接

推薦理由: danswer可以自然語言提問並獲得由私人來源支持的答案,並通過引用和參考來源材料獲得可靠答案,連接到諸如Slack、GitHub、Confluence等工具
官網直達:https://docs.danswer.dev


英文原文

今日推薦英文原文:React Custom Hook: Hovering Made Easy with useHover!

推薦理由:這篇文章介紹了如何創建和使用自定義 React Hook,名為 useHover,用於檢測元素懸停狀態,通過 useState 管理懸停狀態,useEffect 添加懸停事件監聽器,使其可在不同組件中重用,比較實用的 hook


React Custom Hook: Hovering Made Easy with useHover!

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:

img

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! 😄🚀


下載開源日報APP:https://openingsource.org/2579/
加入我們:https://openingsource.org/about/join/
關注我們:https://openingsource.org/about/love/