React Router v6性能调优实战记录
最近在项目中完成了React Router v6的升级,过程中发现了不少性能优化点,今天分享几个实用技巧。
1. 路由懒加载优化
v6版本的lazy功能确实好用,但要注意避免重复加载。我的做法是:
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
// 错误写法 - 会导致重复加载
<Route path="/" element={<Suspense fallback="loading..."><Home/></Suspense>} />
// 正确做法 - 统一管理懒加载组件
const LazyComponent = ({ component: Component, ...props }) => (
<Suspense fallback="loading...">
<Component {...props} />
</Suspense>
);
<Route path="/" element={<LazyComponent component={Home} />} />
2. useNavigate性能陷阱
在高频组件中使用useNavigate时,要注意避免在渲染周期内调用。建议封装成hook:
const useSafeNavigate = () => {
const navigate = useNavigate();
return useCallback((...args) => {
if (navigate) navigate(...args);
}, [navigate]);
};
3. 路由缓存策略
通过useLocation和useParams的组合,可以实现简单的路由缓存:
const useRouteCache = () => {
const location = useLocation();
const [cache, setCache] = useState({});
useEffect(() => {
if (!cache[location.pathname]) {
setCache(prev => ({ ...prev, [location.pathname]: true }));
}
}, [location.pathname]);
return cache;
};
这些优化让应用在v6版本下运行更流畅,建议大家也试试看!

讨论