1. 精准控制useEffect依赖
黄金法则
1 2 3 4 5 6 7 8 9 10 11
| useEffect(() => { fetchData(params.id); }, []);
useEffect(() => { const controller = new AbortController(); fetchData(params.id, { signal: controller.signal }); return () => controller.abort(); }, [params.id]);
|
依赖管理策略
场景 |
解决方案 |
工具支持 |
频繁变化的依赖 |
使用useReducer |
useReducer+dispatch |
对象/数组依赖 |
深度比较或拆解基本类型 |
lodash.isEqual |
函数依赖 |
useCallback包裹 |
eslint-plugin-react-hooks |
2. 自定义Hook工程化实践
数据请求Hook示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| function useFetch<T>(url: string, options?: RequestInit) { const [data, setData] = useState<T | null>(null); const [error, setError] = useState<Error | null>(null); const [loading, setLoading] = useState(true);
useEffect(() => { const abortController = new AbortController(); const fetchData = async () => { try { const response = await fetch(url, { ...options, signal: abortController.signal }); const json = await response.json(); setData(json); } catch (err) { if (!abortController.signal.aborted) { setError(err as Error); } } finally { setLoading(false); } };
fetchData();
return () => abortController.abort(); }, [url, options]);
return { data, error, loading }; }
|
3. 性能优化三重奏
优化策略对比
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function List({ items }) { const filtered = items.filter(...); return <div>{filtered.map(...)}</div>; }
function OptimizedList({ items }) { const filtered = useMemo( () => items.filter(...), [items] ); return <div>{filtered.map(...)}</div>; }
|
渲染性能检测
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { Profiler } from 'react';
const onRender = (id, phase, actualDuration) => { console.log(`${id} ${phase}耗时: ${actualDuration}ms`); };
function App() { return ( <Profiler id="Navigation" onRender={onRender}> <Navigation /> </Profiler> ); }
|
4. 状态提升与上下文共享
Context优化模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| const UserContext = React.createContext<{ user: User; update: (user: User) => void; }>(null!);
function UserProvider({ children }) { const [user, setUser] = useState(initialUser); const updateUser = useCallback((newUser: User) => { setUser(prev => ({ ...prev, ...newUser })); }, []);
const value = useMemo( () => ({ user, update: updateUser }), [user, updateUser] );
return ( <UserContext.Provider value={value}> {children} </UserContext.Provider> ); }
|
5. 复杂状态管理方案
状态机实现示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import { useReducer } from 'react';
const initialState = { status: 'idle', data: null, error: null };
function fetchReducer(state, action) { switch (action.type) { case 'FETCH_START': return { ...state, status: 'pending' }; case 'FETCH_SUCCESS': return { status: 'resolved', data: action.payload, error: null }; case 'FETCH_FAILURE': return { status: 'rejected', data: null, error: action.error }; default: throw new Error(); } }
function useFetchMachine(url) { const [state, dispatch] = useReducer(fetchReducer, initialState);
useEffect(() => { dispatch({ type: 'FETCH_START' }); fetch(url) .then(res => res.json()) .then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data })) .catch(error => dispatch({ type: 'FETCH_FAILURE', error })); }, [url]);
return state; }
|
进阶技巧汇总
- 依赖数组自动化:使用eslint-plugin-react-hooks自动检测依赖缺失
- Hook组合模式:将多个基础Hook组合成复合Hook
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function useWindowSize() { const [size, setSize] = useState({ width: 0, height: 0 }); useEffect(() => { const handler = () => setSize({ width: window.innerWidth, height: window.innerHeight }); window.addEventListener('resize', handler); return () => window.removeEventListener('resize', handler); }, []); return size; }
|
- 调试技巧:使用useWhyDidYouUpdate检测不必要的渲染
总结
通过合理运用这些进阶技巧,开发者可以显著提升React应用的性能和可维护性。建议结合TypeScript类型系统,并持续关注React 19中即将推出的use优化等新特性。
扩展阅读:
- React官方Hooks API参考
- 《Hooks in Depth》视频课程
- React Query状态管理库