My Blog
React Hooks 详解
React Hooks 是 React 16.8 引入的新特性,让你可以在函数组件中使用状态和其他 React 特性。
常用 Hooks
useState
用于在函数组件中添加状态:
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect
用于处理副作用:
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
自定义 Hooks
你可以创建自己的 Hooks 来复用状态逻辑:
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
最佳实践
- 只在最顶层调用 Hooks
- 只在 React 函数中调用 Hooks
- 使用 ESLint 插件来检查 Hooks 规则
- 合理拆分 useEffect
- 优化性能时考虑使用 useMemo 和 useCallback