# React Hooks 的优势和使用场景
## 核心优势
### 1. 简化组件逻辑
Hooks 允许在不编写 class 的情况下使用 state 和其他 React 特性。通过将相关逻辑拆分到独立的 Hook 中,可以显著减少代码量。
```jsx
// 传统 class 组件
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
// 使用 Hook 的函数组件
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
2. 更好的逻辑复用
Hooks 解决了高阶组件和 render props 带来的"嵌套地狱"问题,使逻辑复用更加直观。
// 自定义 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();
// ...
}
3. 更细粒度的代码组织
Hooks 允许按照功能而非生命周期方法来组织代码,使相关代码更加集中。
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
}, [props.friend.id]);
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
主要使用场景
1. 状态管理
useState 是最基础的 Hook,用于在函数组件中添加局部状态。
function Form() {
const [name, setName] = useState('Mary');
const [age, setAge] = useState(25);
return (
<>
<input value={name} onChange={e => setName(e.target.value)} />
<input value={age} onChange={e => setAge(e.target.value)} />
</>
);
}
2. 副作用处理
useEffect 合并了 class 组件中的 componentDidMount、componentDidUpdate 和 componentWillUnmount。
useEffect(() => {
// 组件挂载和更新时执行
document.title = `You clicked ${count} times`;
// 返回的清理函数会在组件卸载时执行
return () => {
document.title = 'React App';
};
}, [count]); // 仅在 count 变化时重新执行
3. 性能优化
useMemo 和 useCallback 可以避免不必要的计算和渲染。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
4. 上下文访问
useContext 可以更方便地访问 Context 值。
const theme = useContext(ThemeContext);
return <div style={{ background: theme.background }} />;
5. 复杂状态逻辑
useReducer 适合管理包含多个子值的复杂 state 逻辑。
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