React Hooks 的优势和使用场景

48 阅读2分钟
# React Hooks 的优势和使用场景

## 1. React Hooks 的优势

### 1.1 简化组件逻辑
Hooks 允许在不编写 class 的情况下使用 state 和其他 React 特性。这使得函数组件能够拥有和类组件相似的功能,同时减少了代码量。

```jsx
// 类组件
class Counter extends React.Component {
  state = { count: 0 };
  
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

// 函数组件 + Hooks
function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

1.2 更好的逻辑复用

Hooks 解决了高阶组件和 render props 带来的"嵌套地狱"问题,通过自定义 Hook 可以轻松地在多个组件之间复用状态逻辑。

// 自定义 Hook
function useCounter(initialValue) {
  const [count, setCount] = useState(initialValue);

  const increment = () => {
    setCount(count + 1);
  };

  return { count, increment };
}

// 使用自定义 Hook
function CounterA() {
  const { count, increment } = useCounter(0);
  return <button onClick={increment}>A: {count}</button>;
}

function CounterB() {
  const { count, increment } = useCounter(10);
  return <button onClick={increment}>B: {count}</button>;
}

1.3 更直观的副作用管理

useEffect 将 componentDidMount、componentDidUpdate 和 componentWillUnmount 合并为一个 API,使得副作用管理更加直观。

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    let isMounted = true;
    
    fetchUser(userId).then(data => {
      if (isMounted) setUser(data);
    });

    return () => {
      isMounted = false; // 清理函数
    };
  }, [userId]); // 依赖数组

  return <div>{user ? user.name : 'Loading...'}</div>;
}

1.4 性能优化更简单

useMemo 和 useCallback 可以轻松实现性能优化,避免不必要的计算和渲染。

function ExpensiveComponent({ list, filter }) {
  const filteredList = useMemo(() => {
    return list.filter(item => item.includes(filter));
  }, [list, filter]); // 只有当 list 或 filter 变化时才重新计算

  return <div>{filteredList.join(', ')}</div>;
}

2. React Hooks 的使用场景

2.1 状态管理

useState 是最基础的 Hook,适用于管理组件内部状态。

function Form() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  return (
    <form>
      <input value={name} onChange={e => setName(e.target.value)} />
      <input value={email} onChange={e => setEmail(e.target.value)} />
    </form>
  );
}

2.2 副作用处理

useEffect 适用于处理数据获取、订阅、手动修改 DOM 等副作用。

function WindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []); // 空数组表示只在挂载和卸载时执行

  return <div>Window size: {size.width}x{size.height}</div>;
}

2.3 上下文访问

useContext 可以方便地访问 React 上下文,避免多层传递 props。

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

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button style={{ background: theme