React Hooks 的优势和使用场景

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

## 1. 代码复用性提升
- **自定义Hook封装逻辑**:将组件逻辑提取到可重用函数中
```jsx
// 使用自定义Hook获取窗口大小
function useWindowSize() {
  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 size;
}

// 在组件中使用
function MyComponent() {
  const { width } = useWindowSize();
  return <div>Window width: {width}px</div>;
}
  • 告别HOC和render props:避免组件嵌套的"wrapper hell"

2. 逻辑关注点分离

  • 按功能组织代码:相关逻辑集中处理
function FriendStatus({ friendId }) {
  // 状态逻辑
  const [isOnline, setIsOnline] = useState(null);

  // 副作用逻辑
  useEffect(() => {
    const handleStatusChange = (status) => setIsOnline(status.isOnline);
    ChatAPI.subscribe(friendId, handleStatusChange);
    return () => ChatAPI.unsubscribe(friendId, handleStatusChange);
  }, [friendId]);

  // UI渲染
  return isOnline ? 'Online' : 'Offline';
}

3. 性能优化更精细

  • useMemo/useCallback减少计算
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
  • useEffect依赖项控制:精确控制副作用执行时机

4. 类组件问题解决

  • 消除this绑定问题:函数组件无需处理this
  • 简化生命周期:useEffect统一处理副作用
// 替代componentDidMount和componentWillUnmount
useEffect(() => {
  // 挂载时执行
  return () => {
    // 卸载时清理
  };
}, []);

5. 状态管理更灵活

  • useReducer处理复杂状态
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, {count: 0});
  return (
    <button onClick={() => dispatch({type: 'increment'})}>
      Count: {state.count}
    </button>
  );
}

6. 使用场景推荐

  1. 表单处理:useState + useEffect
  2. 数据获取:useEffect + useState/useReducer
  3. DOM操作:useRef
  4. 全局状态:useContext + useReducer
  5. 动画效果:useEffect + requestAnimationFrame
  6. 第三方库集成:自定义Hook封装

7. 最佳实践

  1. Hook调用顺序稳定:不要在条件/循环中使用Hook
  2. 合理拆分Hook:每个Hook只关注单一功能
  3. 性能优化:正确设置依赖数组
  4. 自定义Hook命名:以use开头
  5. TypeScript支持:为Hook提供完整类型定义

8. 注意事项

  • 不可在普通JS函数中使用:只在React函数组件或自定义Hook中使用
  • 避免过度使用useEffect:考虑是否可以用事件处理替代
  • 复杂状态考虑useReducer:当useState变得难以维护时