storyblok / storyblok-react

React SDK for Storyblok CMS
MIT License
122 stars 37 forks source link

The storyblok instance should provide the ability to set components, after initialized. #595

Closed noblica closed 1 year ago

noblica commented 1 year ago

Description

As a developer using SB with NextJS, I would like to keep my page bundles as small and performant as possible.

Setting up @storyblok/react using the currently proposed method in the tutorial is not optimal, because it loads all components passed to the storyblokInit function, on all pages. Which means that, if there are pages that use only a small number of components (or maybe none at all because they are hard coded static pages), they will still get their load times slowed down by the big bundle of JS that needs to load, regardless if these components are used on that page or not.

This happens because these imports are statically passed in the _app file, which is loaded on every page in NextJS

Suggested solution or improvement

Add and expose a method to set/append the components in the initialized SB method, in this file

export const setComponentsMap = (newComponentsMap: SbReactComponentsMap = {}) => {
  componentsMap = newComponentsMap;
};

I can also fork the repo and do this via a PR, just let me know.

Additional context

We have gotten around this by executing storyblokInit in the _app.tsx without any components defined, like so:

storyblokInit({
  accessToken: PREVIEW_TOKEN,
  use: [apiPlugin],
});

and then additionally executing it on every page, with the components needed just for that page.

storyblokInit({
  accessToken: PREVIEW_TOKEN,
  use: [apiPlugin],
  components: {
      "cta-simple": CtaSimple,
      "faq-grid": FaqGrid,
      "rich-text": RichText,
  ...
  }
});

The issue with this workaround is that it seems that it executes a Content Management API call, which SB limits to 6 per second. So if multiple pages are built at the same time, we hit the API call limit, and our build fails.

Validations

fgiuliani commented 1 year ago

Hi @noblica thanks for your suggestion.

If you want and you can, please go ahead and create a PR with the changes. We can later discuss on it to get to the point where we introduce the changes to the SDK. What do you think?

noblica commented 1 year ago

Hey @fgiuliani thanks for the feedback.

I have created a PR for this and linked it to this ticket. Please let me know if this is fine or if more work is needed :slightly_smiling_face:

fgiuliani commented 1 year ago

Thank you very much for your contribution @noblica! As the PR is already merged, I'm closing this issue

alexjoverm commented 1 year ago

Thanks @noblica ! Great PR