Lazy loading is a technique used to improve the performance of applications by dynamically loading components only when they are needed. Instead of loading all components when the application starts, lazy loading allows components to be loaded asynchronously, typically when they are about to be rendered on the screen.
Lazy loading allows you to split your application into smaller chunks and load them asynchronously, which can significantly improve initial loading times. When lazy loading is combined with routing, you can dynamically load different parts of your application based on the route the user navigates to.
How to reproduce the Uncaught runtime error
function App() {
return (
<div className="App">
<h1>React Router - Lazy loading demo</h1>
<Outlet />
</div>
);
}
export default App;
Error
Uncaught runtime errors:
ERROR
A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.
at throwException (http://localhost:3000/static/js/bundle.js:26909:39)
at handleError (http://localhost:3000/static/js/bundle.js:33103:11)
at renderRootSync (http://localhost:3000/static/js/bundle.js:33214:11)
at recoverFromConcurrentError (http://localhost:3000/static/js/bundle.js:32703:24)
at performSyncWorkOnRoot (http://localhost:3000/static/js/bundle.js:32912:24)
at flushSyncCallbacks (http://localhost:3000/static/js/bundle.js:20905:26)
at http://localhost:3000/static/js/bundle.js:32535:17
Solution #1
To resolve the mentioned React Router lazy loading error wrap the <Outlet/> component in the <Suspense>
component.
function App() {
return (
<div className="App">
<h1>React Router - Lazy loading demo</h1>
<Suspense fallback={<div>Loading...</div>}>
<Outlet />
</Suspense>
</div>
);
}
export default App;
Solution #2
To resolve the mentioned React Router lazy loading error update your route definition. Wrap the affected component in the <Suspense>
component.
<Route
path="/page-1"
element={
<Suspense fallback={<div>Loading...</div>}>
<Page1 />
</Suspense>
}
/>