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>;
}

// 优化后组件:使用useMemo缓存
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
// 使用React DevTools的Profiler组件
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
// 创建优化的Context
const UserContext = React.createContext<{
user: User;
update: (user: User) => void;
}>(null!);

function UserProvider({ children }) {
const [user, setUser] = useState(initialUser);

// 使用useCallback避免Provider值不必要变化
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;
}

进阶技巧汇总

  1. 依赖数组自动化:使用eslint-plugin-react-hooks自动检测依赖缺失
  2. 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;
    }
  3. 调试技巧:使用useWhyDidYouUpdate检测不必要的渲染

总结

通过合理运用这些进阶技巧,开发者可以显著提升React应用的性能和可维护性。建议结合TypeScript类型系统,并持续关注React 19中即将推出的use优化等新特性。

扩展阅读

  • React官方Hooks API参考
  • 《Hooks in Depth》视频课程
  • React Query状态管理库