React Hooks 完全指南
原创2024/1/10大约 2 分钟
React Hooks 完全指南
React Hooks 改变了我们编写 React 组件的方式,让函数组件拥有了状态管理和生命周期的能力。
什么是 Hooks
Hooks 是 React 16.8 引入的新特性,允许你在不编写 class 的情况下使用 state 和其他 React 特性。
常用 Hooks
useState
管理组件状态:
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
)
}useEffect
处理副作用:
import { useState, useEffect } from 'react'
function UserProfile({ userId }) {
const [user, setUser] = useState(null)
useEffect(() => {
fetchUser(userId).then(setUser)
// 清理函数
return () => {
cancelRequest()
}
}, [userId]) // 依赖数组
return <div>{user?.name}</div>
}useContext
使用 Context:
import { useContext } from 'react'
import { ThemeContext } from './ThemeContext'
function ThemedButton() {
const theme = useContext(ThemeContext)
return (
<button style={{ background: theme.background }}>
Themed Button
</button>
)
}useRef
访问 DOM 或保存可变值:
import { useRef, useEffect } from 'react'
function TextInput() {
const inputRef = useRef(null)
useEffect(() => {
inputRef.current.focus()
}, [])
return <input ref={inputRef} />
}useMemo & useCallback
性能优化:
import { useMemo, useCallback } from 'react'
function ExpensiveComponent({ data }) {
// 缓存计算结果
const processedData = useMemo(() => {
return data.map(item => heavyComputation(item))
}, [data])
// 缓存函数引用
const handleClick = useCallback(() => {
console.log('Clicked')
}, [])
return <div onClick={handleClick}>{processedData}</div>
}自定义 Hooks
创建可复用的逻辑:
// useLocalStorage.js
import { useState, useEffect } from 'react'
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const stored = localStorage.getItem(key)
return stored ? JSON.parse(stored) : initialValue
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue]
}
// 使用
function App() {
const [name, setName] = useLocalStorage('name', 'Guest')
return (
<input
value={name}
onChange={e => setName(e.target.value)}
/>
)
}Hooks 规则
- 只在最顶层使用 Hooks: 不要在循环、条件或嵌套函数中调用
- 只在 React 函数中调用 Hooks: 函数组件或自定义 Hooks
最佳实践
- 合理拆分 useEffect
- 使用 ESLint 插件检查 Hooks 规则
- 避免过度优化(useMemo/useCallback)
- 保持自定义 Hooks 的单一职责
总结
React Hooks 让函数组件变得更加强大和灵活,是现代 React 开发的核心。