React Hooks 是 React 16.8 版本引入的新特性,它允许你在不编写类的情况下使用 state 和其他 React 特性。以下是一些关于 React Hooks 的基本概念和用法。

常用 Hooks

  1. useState

    • 用于在函数组件中添加 state。
    • 示例:const [count, setCount] = useState(0);
  2. useEffect

    • 用于在组件中执行副作用操作,如数据获取、订阅或手动更改 DOM。
    • 示例:useEffect(() => { fetch(...); }, [count]);
  3. useContext

    • 用于访问 React 上下文(Context)中的值。
    • 示例:const theme = useContext(ThemeContext);
  4. useReducer

    • 用于替代 useState,在更复杂的状态逻辑中更方便地使用。
    • 示例:const [state, dispatch] = useReducer(reducer, initialState);
  5. useCallback

    • 返回一个记忆化的回调函数。
    • 示例:const memoizedCallback = useCallback(() => { /* ... */ }, [a, b]);
  6. useMemo

    • 返回一个记忆化的值。
    • 示例:const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

图片示例

React Hooks 的概念可以类比成“钩子”,这里有一个可爱的钩子图片:

hook

扩展阅读

想要了解更多关于 React Hooks 的内容,可以阅读以下文章: