# 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]);
return isOnline ? 'Online' : 'Offline';
}
3. 性能优化更精细
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => doSomething(a, b), [a, b]);
- useEffect依赖项控制:精确控制副作用执行时机
4. 类组件问题解决
- 消除this绑定问题:函数组件无需处理this
- 简化生命周期:useEffect统一处理副作用
useEffect(() => {
return () => {
};
}, []);
5. 状态管理更灵活
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. 使用场景推荐
- 表单处理:useState + useEffect
- 数据获取:useEffect + useState/useReducer
- DOM操作:useRef
- 全局状态:useContext + useReducer
- 动画效果:useEffect + requestAnimationFrame
- 第三方库集成:自定义Hook封装
7. 最佳实践
- Hook调用顺序稳定:不要在条件/循环中使用Hook
- 合理拆分Hook:每个Hook只关注单一功能
- 性能优化:正确设置依赖数组
- 自定义Hook命名:以use开头
- TypeScript支持:为Hook提供完整类型定义
8. 注意事项
- 不可在普通JS函数中使用:只在React函数组件或自定义Hook中使用
- 避免过度使用useEffect:考虑是否可以用事件处理替代
- 复杂状态考虑useReducer:当useState变得难以维护时