Efficiently Load Storyblok Components in React
Storyblok is the first headless CMS that works for developers & marketers alike.
When you use Storyblok with a React-based framework, you load all blocks as components when you initialize the SDK with storyblokInit
. This is typically handled in a layout page that lets all pages access all components. Here's what the code might look like:
storyblokInit({
accessToken,
use: [apiPlugin],
components: {
// all your components
},
})
Storyblok's SDK automatically renders these predefined components based on the page content.
While convenient, this approach may lead to larger bundle sizes and slower page loads, and can be particularly problematic when using heavy JavaScript libraries on specific pages or components.
When you build a site with React, you should be mindful of how much JavaScript is sent to users and import and load only what's necessary on each page.
How to solve the problem?
Several tools help you tackle this challenge and improve performance and user experience. Which alternative you choose depends on your configuration and use case:
- Storyblok's
setComponents
Storyblok's React SDK provides thesetComponents
function that lets you load the components needed for each route instead of defining all of them during initialization. But there's a caveat: this approach is impractical if you use a catch-all route, such as[...slug].xxx
, which is common in most frameworks. - React's
lazy
andSuspense
React provides built-in techniques to optimize performance using thelazy
API with theSuspense
component. The initial problem is even less relevant if you adopt React Server Components (RSC), which handle tree-shaking and loading optimizations.
To learn more about importing components more efficiently, visit React's official documentation. - Next.js
Dynamic
In a Next.js project, you can use thedynamic
package, a composite of React's native techniques mentioned above. Dynamic imports allow you to defer the loading of client components and speed up the initial page load.
To learn more about lazy loading components, visit Next.js' official documentation.
Pick one of these techniques to ensure your site loads components and dependencies only when necessary and deliver a better experience to your visitors.