react如何记
React 状态管理基础
React 提供了 useState 和 useReducer 等钩子函数来管理组件的内部状态。useState 是最常用的方法,适用于简单状态:

import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // 初始化状态为0
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
复杂状态逻辑处理
对于需要多个子状态或复杂逻辑的场景,useReducer 更合适:

import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<button onClick={() => dispatch({ type: 'increment' })}>
Count: {state.count}
</button>
);
}
全局状态管理方案
跨组件共享状态可使用 Context API 或第三方库(如 Redux、Zustand):
import { createContext, useContext } from 'react';
const CountContext = createContext();
function Parent() {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
<Child />
</CountContext.Provider>
);
}
function Child() {
const { count, setCount } = useContext(CountContext);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
性能优化注意事项
避免不必要的重新渲染:
- 使用
React.memo包裹组件 - 通过
useCallback缓存函数 - 使用
useMemo缓存计算结果
const MemoizedComponent = React.memo(function MyComponent(props) {
/* 仅在 props 变化时重新渲染 */
});
const cachedFn = useCallback(() => {
// 函数逻辑
}, [dependencies]);
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);






