Display Fallbacks with React.Suspense

Learn how you can render a component tree in the background and simultaneously display a message while the components are loading.

The fallback prop

Firstly, the Suspense component on the React object was named “Placeholder". This is a very accurate description of the task it fulfills: it acts like a placeholder for components that have not yet been rendered and displays alternative content in the meantime. These placeholders can take many forms. They can be a message that parts of the application are still being loaded or take the form of a loading animation. The placeholder we want to display is passed to Suspense in the fallback prop, and must be defined. Any valid React element can be used and passed as a prop. Strings like the following are also valid:

<Suspense fallback="Loading ...">[…]</Suspense>

As long as the component you want to lazy load has not fully loaded, all children of the Suspense element will be replaced with the indicated fallback placeholder. Additionally, no limits on the number of React.lazy() component imports are enforced. The fallback placeholder will be shown until all components have loaded and can be displayed.

Nesting Suspense elements

Nesting components can be a great idea in certain scenarios. When there are parts of the site that are slightly less important and might interfere with the rendering of the primary user interface, it’s recommended to wrap these parts of the application or the component tree in their own Suspense element. This will boost performance and drive the important parts of the application to load first.

A possible scenario to use Suspense in practice is image editing. It can be useful to display the image the user will edit before the user interface finishes loading. The rest of the user interface containing the actual editing functionality will be loaded in a further step if loading the actual component is taking longer. Let’s look at an example.

Get hands-on with 1400+ tech skills courses.