# React Hooks 的优势和使用场景
## 1. React Hooks 的核心优势
### 1.1 简化组件逻辑
Hooks 允许在不编写 class 的情况下使用 state 和其他 React 特性。通过将相关逻辑拆分为更小的函数,而不是强制按生命周期方法拆分,使代码更易于理解和维护。
```jsx
// 传统 class 组件
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Clicked {this.state.count} times
</button>
);
}
}
// 使用 Hooks 的函数组件
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
1.2 更好的代码复用
自定义 Hook 可以提取组件逻辑到可重用的函数中,解决了传统 Mixins 和 HOC 模式带来的问题。
// 自定义 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();
return <div>Window width: {width}</div>;
}
1.3 更直观的副作用管理
useEffect
将相关副作用逻辑组织在一起,比 class 组件中分散在不同生命周期方法中的代码更清晰。
// 传统生命周期方法
class Example extends React.Component {
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
}
// 使用 useEffect
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 仅在 count 变化时执行
}
2. 主要 Hooks 的使用场景
2.1 useState
管理组件内部状态,适用于:
- 表单输入控制
- 开关状态
- 简单的计数器
function Form() {
const [name, setName] = useState('');
return (
<input
value={name}
onChange={e => setName(e.target.value)}
placeholder="Enter your name"
/>
);
}
2.2 useEffect
处理副作用操作,适用于:
- 数据获取
- 订阅事件
- 手动 DOM 操作
- 定时器
function DataFetcher({ id }) {
const [data, setData] = useState(null);
useEffect(() => {
let isMounted = true;
fetch(`/api/data/${id}`)
.then(res => res.json())
.then(data => isMounted && setData(data));
return () => { isMounted = false }; // 清理函数
}, [id]); // id 变化时重新获取
return <div>{data ? data.name : 'Loading...'}</div>;
}
2.3 useContext
跨组件共享状态,适用于:
- 主题切换
- 用户认证信息
- 全局配置
const ThemeContext = React.createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div style={{ background: theme === 'dark' ? '#333' : '#fff' }} />;
}
2.4 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();
}