React Hooks 最佳实践
useState 的使用技巧
当状态逻辑比较复杂时,使用 reducer 可能比多个 useState 更好:
const [state, dispatch] = useReducer(reducer, initialState);
useEffect 的注意事项
- 清理副作用
- 正确使用依赖数组
- 避免无限循环
useEffect(() => {
const subscription = someAPI.subscribe();
// 清理函数
return () => {
subscription.unsubscribe();
};
}, [someAPI]); // 明确的依赖项
自定义 Hook
创建自定义 Hook 可以复用状态逻辑:
function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
// ... 实现逻辑
return size;
}
合理使用 Hooks 可以让你的 React 代码更加清晰和易于维护。