React Hooks 深入解析

前端开发
React Hooks 深入解析

React Hooks 简介

React Hooks 是 React 16.8 引入的新特性,它让你在不编写 class 的情况下使用 state 和其他 React 特性。

useState

useState 是最基本的 Hook,用于在函数组件中添加状态。

import { useState } from ''react'';

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <button onClick={() => setCount(count + 1)}>
      点击了 {count} 次
    </button>
  );
}

useEffect

useEffect 用于处理副作用,如数据获取、订阅等。

import { useState, useEffect } from ''react'';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  }, [userId]);
  
  if (!user) return <div>加载中...</div>;
  return <div>{user.name}</div>;
}

useContext

useContext 让你可以订阅 React 的 Context。

const ThemeContext = React.createContext(''light'');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>主题按钮</button>;
}

自定义 Hooks

你可以创建自己的 Hooks 来复用状态逻辑:

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });
  
  const setValue = (value) => {
    setStoredValue(value);
    window.localStorage.setItem(key, JSON.stringify(value));
  };
  
  return [storedValue, setValue];
}

最佳实践

  1. 只在顶层调用 Hooks - 不要在循环、条件或嵌套函数中调用
  2. 只在 React 函数中调用 - 不要在普通 JavaScript 函数中调用
  3. 使用 ESLint 插件 - eslint-plugin-react-hooks 可以帮助你遵循这些规则