# React Hooks 的优势和使用场景
## 1. React Hooks 的核心优势
### 1.1 简化组件逻辑
Hooks 允许在不编写 class 的情况下使用 state 和其他 React 特性。通过将相关逻辑组织到独立的 Hook 中,可以更清晰地分离关注点。
```javascript
// 传统 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>
);
}
1.2 更好的代码复用
自定义 Hook 可以提取组件逻辑到可重用的函数中,解决了高阶组件和渲染属性模式带来的"嵌套地狱"问题。
// 自定义 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 将生命周期方法统一为一个 API,使副作用代码更集中且易于理解。
useEffect(() => {
// 相当于 componentDidMount 和 componentDidUpdate
document.title = `You clicked ${count} times`;
// 返回的函数相当于 componentWillUnmount
return () => {
document.title = 'React App';
};
}, [count]); // 仅在 count 变化时更新
2. 主要 Hooks 的使用场景
2.1 useState
管理组件内部状态,适用于需要响应式更新的数据。
const [state, setState] = useState(initialState);
2.2 useEffect
处理副作用操作,如数据获取、订阅、手动修改 DOM 等。
useEffect(() => {
// 副作用逻辑
}, [dependencies]);
2.3 useContext
在函数组件中访问 React 上下文,避免多层传递 props。
const value = useContext(MyContext);
2.4 useReducer
适用于复杂状态逻辑,特别是当 state 逻辑较复杂或包含多个子值时。
const [state, dispatch] = useReducer(reducer, initialState);
2.5 useCallback & useMemo
性能优化 Hook,避免不必要的重新计算和渲染。
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
2.6 useRef
访问 DOM 节点或存储可变值而不触发重新渲染。
const inputEl = useRef(null);
<input ref={inputEl} type="text" />
3. 高级应用场景
3.1 自定义 Hook 封装业务逻辑
将复杂业务逻辑封装为可复用的 Hook。
function useFormInput(initialValue) {
const [value, setValue] = useState(initialValue);
function handleChange(e) {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
};
}
function MyForm() {
const name = useFormInput('Mary');
return <input {...name} />;
}
3.2 状态管理与 Context 结合
构建轻量级状态管理方案。
function useStore() {
const [state, dispatch] = useReducer(reducer, initialState);
const getState = useCallback(() => state, [state]);
return { getState, dispatch };
}
const StoreContext = createContext(null);
function StoreProvider({ children }) {
const store = useStore();
return (
<StoreContext