Keep the Current Page Rendered Until the New Page is Loaded with React.lazy and React.Suspense

Is your app jumping away before the lazy component finishes loading? Here’s how to keep the old page visible until the new one’s ready.

Summarize with AI

Not enough time? get the key points instantly.

Why am I getting this problem?

By default, when a lazily‐loaded component isn’t yet ready, immediately shows its fallback UI. If that’s just a spinner or blank screen, your app “jumps” away from the current page before the new one arrives, creating a jarring flash.

Solution

You can capture and reuse the last‐rendered route component as the fallback, so it stays visible until the new one is ready. Below is a beginner‑friendly, step‑by‑step example using React‐Router v6.

1. Define your lazy routes

This code shows how to lazily load each route component on demand in a React development project.

// routes.jsimport React, { lazy } from ‘react’;

 

export const routes = [

  { path: ‘/’, element: lazy(() => import(‘./Home’)) },

  { path: ‘/about’, element: lazy(() => import(‘./About’)) },

];

2. Create a wrapper that tracks the last element

Here we wrap your routes in Suspense and keep the previous view until the new one finishes loading.

//App.jsimport { useState, useEffect } from ‘react’;

import { BrowserRouter, useLocation, useRoutes } from ‘react-router-dom’;

import { routes } from ‘./routes’;

import React, { Suspense } from ‘react’;

 

function AppWrapper() {

  const location = useLocation();

  const element = useRoutes(routes);

  const [lastRendered, setLastRendered] = useState(element);

 

  // Whenever the route changes, remember the previous element

  useEffect(() => {

    setLastRendered(element);

  }, [location, element]);

 

  return (

    // Use the lastRendered as the fallback until the new element loads

    

      {element}

    

  );

}

 

export default function App() {

  return (

    

      

    

  );

}

3. Breakdown of how it works

  1. useRoutes(routes) returns the element for the current path.
  2. We store that element in lastRendered every time the location or element changes.
  3. Wrapping in means:
    • While loading the new lazy component, render lastRendered (the old page).
    • Once loaded, replace it seamlessly with the new page.

Worth Reading:

Key Takeaways

  • Capture the outgoing route element in state.
  • Use that state as your fallback.
  • This ensures no blank screen or spinner replaces your current page until the new one is ready.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

ReactJS

Filter Items Based On Multiple Properties

Why am I getting this problem? If you apply separate filters in sequence or only check one property at a time your code will match…