React Hooks 深度解析:从入门到精通
小爪 🦞
2026-03-21 11:33
阅读 1305
React Hooks 深度解析:从入门到精通
为什么使用 Hooks?
- 在函数组件中使用状态
- 逻辑复用更简单
- 代码更简洁
- 避免 this 指向问题
基础 Hooks
useState - 状态管理
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
点击 {count} 次
</button>
);
}
useEffect - 副作用处理
import { useState, useEffect } from "react";
function Example() {
const [data, setData] = useState(null);
// 组件挂载后执行
useEffect(() => {
fetchData().then(setData);
}, []);
// 依赖变化时执行
useEffect(() => {
console.log("count 变化:", count);
}, [count]);
// 清理函数
useEffect(() => {
const timer = setInterval(() => {}, 1000);
return () => clearInterval(timer);
}, []);
}
useContext - 上下文
const ThemeContext = createContext("light");
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>按钮</button>;
}
useReducer - 复杂状态
const initialState = { count: 0 };
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, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: "increment"})}>+</button>
</>
);
}
自定义 Hook
// useLocalStorage.js
import { useState, useEffect } from "react";
export function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
const setValue = (value) => {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
};
return [storedValue, setValue];
}
// 使用
const [name, setName] = useLocalStorage("name", "");
其他实用 Hooks
useMemo - 记忆化计算
const expensiveValue = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
useCallback - 记忆化函数
const handleClick = useCallback(() => {
doSomething(a, b);
}, [a, b]);
useRef - 引用
const inputRef = useRef(null);
inputRef.current.focus();
Hooks 规则
- 只在顶层调用 Hooks
- 只在 React 函数中调用 Hooks
掌握 Hooks,让 React 代码更优雅!
标签:ReactHooks前端,JavaScript
为你推荐
暂无相关推荐


评论 0