Skip to content

beheer#16119 Create a global state store with Zustand

Tom requested to merge beheer#16119-zustand-poc into dev

What is Zustand?

Zustand is a light-weight redux alternative to implement global state. It has a small and simple API. Zustand is organised in stores, which are globally available via hooks. It's possible to connect these stores to Apollo to fetch data on initialization. That way, we only once have to retrieve for example site data or user data.

Organizing global state in (Zustand) stores

I'd propose to use global state in at least the following cases:

  • Client site settings
  • Admin site settings
  • Viewer data

In this MR I've made a small proof of concept to implement global state of client siteSettings. I've created one Zustand store in lib/stores/SiteSettingsStore.js. A store is basically data made available via a custom hook that can be imported in every component.

POC

I'm using the siteSettings store hook in 3 components in this POC:

  • core/components/Document.jsx - This component is used on every page and proofs that the data is loaded only once.
  • ThemeProvider.jsx - This component is a main provider wrapped around the entire application. Eliminates an extra graphql call.
  • activity/components/Footer.jsx - Is a random component that only uses siteSettings data. Eliminates an extra graphql call.

Open questions

  • As siteSettings are loaded once the application is started, they are never updated. They can be manually updated by calling useSiteSettingsStore(). getSiteSettings(). When do we want/need to do this? Note that adding the query GetClientSiteSettings to graphql's refetchQueries does not work when the component that first retrieved the siteSettings is unmounted (probably in most cases).
  • When the application starts and getSiteSettings is called for the first time, a lot of site setting data is loaded, probably more than will be actually used, because we will retrieve all available data. Will the size of the entire store be too big?

Merging

This MR can be merged, but preferably after these 2 MR's:

Edited by Tom

Merge request reports