React Hooks 的优势和使用场景

95 阅读1分钟
# React Hooks 的优势和使用场景

## 1. 代码复用性提升
- **自定义Hook封装逻辑**:可将组件逻辑提取到可重用的函数中
```jsx
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;
}
// 在任何组件中调用:const { width } = useWindowSize();
  • 替代HOC和Render Props:避免组件嵌套地狱
// 替代前(HOC模式)
const EnhancedComponent = withHOC(MyComponent);

// 替代后(Hook模式)
function MyComponent() {
  const hocData = useHOCData();
  return <div>{hocData}</div>;
}

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. 性能优化更精细

  • memoization优化:useMemo/useCallback避免重复计算
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
  • 精准控制更新:依赖项数组细粒度控制effect执行
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // 仅在count变化时更新

4. 生命周期简化

  • useEffect统一处理:合并componentDidMount/componentDidUpdate
useEffect(() => {
  // 相当于componentDidMount + componentDidUpdate
  console.log('mounted or updated');
  return () => {
    // 相当于componentWillUnmount
    console.log('cleanup');
  };
}, [dependencies]);

5. 状态管理更灵活

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

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

6. 使用场景指南

  1. 表单处理:useState管理表单状态
function Form() {
  const [inputs, setInputs] = useState({});
  const handleChange = e => setInputs({...inputs, [e.target.name]: e.target.value});
  // ...
}
  1. 数据获取:useEffect+useState组合
function User({ userId }) {
  const [user, setUser] = useState(null);
  useEffect(() => {
    fetchUser(userId).then(data => setUser(data));
  }, [userId]);
  // ...
}
  1. 全局状态:useContext共享状态
const ThemeContext = createContext('light');
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}
function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div style={{ background: theme }}>...</div>;
}
  1. 动画效果:useRef+useEffect实现
function FadeIn({ children }) {
  const ref = useRef(null);
  useEffect(() => {
    ref.current.style.transition = 'opacity 500ms';
    ref.current