React Hooks 的优势和使用场景

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

## 1. React Hooks 的核心优势

### 1.1 简化组件逻辑
Hooks 允许在不编写 class 的情况下使用 state 和其他 React 特性。通过将相关逻辑拆分为更小的函数,而不是强制按生命周期方法拆分,使代码更易于理解和维护。

```jsx
// 传统 class 组件
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  
  // 必须拆分到不同生命周期方法
  componentDidMount() {
    document.title = `Count: ${this.state.count}`;
  }
  
  componentDidUpdate() {
    document.title = `Count: ${this.state.count}`;
  }
  
  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Count: {this.state.count}
      </button>
    );
  }
}

// 使用 Hooks 的函数组件
function Counter() {
  const [count, setCount] = useState(0);
  
  // 相关逻辑集中在一起
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

1.2 更好的代码复用

自定义 Hook 可以提取组件逻辑到可重用的函数中,解决了高阶组件和渲染属性模式带来的"嵌套地狱"问题。

// 自定义 Hook
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  
  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return width;
}

// 在多个组件中复用
function MyComponent() {
  const width = useWindowWidth();
  return <div>Window width: {width}</div>;
}

1.3 更直观的副作用管理

useEffect 将相关副作用逻辑组织在一起,通过依赖数组明确控制执行时机,比生命周期方法更精确。

useEffect(() => {
  // 相当于 componentDidMount 和 componentDidUpdate
  const subscription = props.source.subscribe();
  
  // 相当于 componentWillUnmount
  return () => {
    subscription.unsubscribe();
  };
}, [props.source]); // 仅在 props.source 改变时重新订阅

2. 主要 Hooks 的使用场景

2.1 useState - 状态管理

适用于函数组件中的局部状态管理,替代类组件的 this.state。

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 UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    let isMounted = true;
    
    fetchUser(userId).then(data => {
      if (isMounted) setUser(data);
    });
    
    return () => {
      isMounted = false; // 清理未完成的请求
    };
  }, [userId]); // 当 userId 变化时重新获取
}

2.3 useContext - 跨组件共享状态

无需组件层层传递 props 即可访问 React Context 值。

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

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div style={{ background: theme === 'dark' ? '#333' : '#FFF' }} />;
}

2.4 useReducer - 复杂状态逻辑

适合管理包含多个子值的 state 对象,或当下一个 state 依赖于前一个 state 的情况。

function todosReducer(state, action) {
  switch (action.type) {
    case 'add':
      return [...state, { text: action.text, completed: false