React Hooks
8 methodsReact 函数组件中使用的状态与副作用钩子集合。
useState(initial)声明组件内部状态,返回当前值与更新函数。
Parameters
| Name | Type | Description |
|---|---|---|
| initial | any | (() => any) | 初始状态值或惰性初始化函数。 |
Returns
返回 [state, setState] 二元组,state 为当前值,setState 为更新函数。
Example
react
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
const [user, setUser] = useState({ name: 'Tom', age: 20 });useEffect(setup, deps)在渲染后执行副作用,可选依赖数组控制执行时机,返回清理函数。
Parameters
| Name | Type | Description |
|---|---|---|
| setup | () => void | (() => void) | 副作用函数,可返回清理函数。 |
| deps | Array | 依赖数组;空数组仅执行一次,省略则每次都执行。 |
Returns
无返回值;setup 返回的清理函数会在组件卸载或依赖变化前调用。
Example
react
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(id);
}, []);
useEffect(() => {
document.title = `Seconds: ${seconds}`;
}, [seconds]);
return <span>{seconds}s</span>;
}useContext(context)读取并订阅 React 上下文,Context 值变化时触发重渲染。
Parameters
| Name | Type | Description |
|---|---|---|
| context | Context | 由 createContext 创建的上下文对象。 |
Returns
返回当前 Context 的 Provider 提供的 value。
Example
react
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click me</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}useReducer(reducer, initial)使用 reducer 模式管理复杂状态逻辑,返回当前状态与 dispatch 函数。
Parameters
| Name | Type | Description |
|---|---|---|
| reducer | (state, action) => state | 状态转换纯函数。 |
| initial | any | (() => any) | 初始状态或惰性初始化函数。 |
Returns
返回 [state, dispatch] 二元组。
Example
react
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}useRef(initial)创建跨渲染保持的可变引用对象,修改不会触发重渲染。
Parameters
| Name | Type | Description |
|---|---|---|
| initial | any | ref.current 的初始值。 |
Returns
返回 { current: initial } 形式的 ref 对象。
Example
react
import { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const focus = () => inputRef.current.focus();
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focus}>Focus</button>
</>
);
}
const timerRef = useRef(null);useMemo(factory, deps)记忆化计算结果,仅当依赖变化时重新计算。
Parameters
| Name | Type | Description |
|---|---|---|
| factory | () => any | 返回记忆值的计算函数。 |
| deps | Array | 依赖数组。 |
Returns
返回 factory 的计算结果。
Example
react
import { useMemo, useState } from 'react';
function ExpensiveList({ items, filter }) {
const filtered = useMemo(() => {
console.log('Filtering...');
return items.filter(item => item.includes(filter));
}, [items, filter]);
return <ul>{filtered.map((item, i) => <li key={i}>{item}</li>)}</ul>;
}useCallback(fn, deps)记忆化函数引用,避免因函数重建导致的子组件无谓重渲染。
Parameters
| Name | Type | Description |
|---|---|---|
| callback | Function | 需要记忆化的回调函数。 |
| deps | Array | 依赖数组。 |
Returns
返回记忆化后的函数,仅当依赖变化时才更新。
Example
react
import { useCallback, useState } from 'react';
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []);
return <Child onClick={handleClick} count={count} />;
}
const Child = React.memo(function Child({ onClick, count }) {
return <button onClick={onClick}>Clicked {count} times</button>;
});useLayoutEffect(setup, deps)与 useEffect 类似,但在 DOM 更新后同步执行,适合读取布局信息。
Parameters
| Name | Type | Description |
|---|---|---|
| setup | () => void | (() => void) | 同步副作用函数,可返回清理函数。 |
| deps | Array | 依赖数组。 |
Returns
无返回值;清理函数在依赖变化或卸载前同步执行。
Example
react
import { useLayoutEffect, useRef, useState } from 'react';
function Tooltip({ targetRef }) {
const tooltipRef = useRef(null);
const [pos, setPos] = useState({ x: 0, y: 0 });
useLayoutEffect(() => {
if (targetRef.current && tooltipRef.current) {
const rect = targetRef.current.getBoundingClientRect();
setPos({ x: rect.left, y: rect.top - 30 });
}
}, [targetRef]);
return <div ref={tooltipRef} style={{ position: 'fixed', left: pos.x, top: pos.y }}>Tip</div>;
}