Blog>
Snippets

Optimizing SSR Performance with Code Splitting

Showcase how to implement code splitting in a server-side rendered React application to optimize load times.
import { createBrowserRouter, Route, RouterProvider } from 'react-router-dom';
import { lazy } from 'react';

// Dynamically imported components for code splitting
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));

// Creating routes with dynamic imports
const router = createBrowserRouter([
  {
    path: '/',
    element: <Home />
  },
  {
    path: '/about',
    element: <About />
  }
]);
This snippet creates a router using createBrowserRouter from 'react-router-dom' and employs React's lazy for code splitting by dynamically importing components. Each route associated with a component only loads when needed, optimizing SSR performance by reducing the initial load time.
import { Suspense } from 'react';
import { renderToString } from 'react-dom/server';

const App = () => (
  <Suspense fallback={<div>Loading...</div>}>
    <RouterProvider router={router} />
  </Suspense>
);

// Server-side rendering with suspense for dynamic imports
const html = renderToString(<App />);
In server-side rendering, this code wraps the RouterProvider in a Suspense component, allowing React to wait for the dynamically imported components to load. The fallback prop displays a loading message, improving user experience while components are loaded lazily.