Blog>
Snippets

Dynamic Import of Redux Stores

Present a code snippet to dynamically import Redux stores as ES Modules using the `import()` function, which allows for code-splitting and on-demand loading in a project.
async function loadStoreModule(moduleName) {
  // Dynamically import the redux store module.
  const storeModule = await import(`./stores/${moduleName}`);
  // Ensure the imported module has a 'default' export which is the store.
  if (!storeModule.default) {
    throw new Error(`${moduleName} does not have a default export`);
  }
  // Return the store from the imported module.
  return storeModule.default;
}
Defines an asynchronous function `loadStoreModule` which takes a module name as an argument, dynamically imports the corresponding Redux store module found under the `./stores/` directory, ensures that it has a default export (which should be the Redux store), and returns this store.
loadStoreModule('userStore').then(userStore => {
  // Use the dynamically imported userStore.
  console.log('User store loaded:', userStore);
}).catch(error => {
  // Handle any errors that might occur during the import.
  console.error('Failed to load the store module:', error);
});
This snippet uses the `loadStoreModule` function defined earlier to import the 'userStore' module dynamically. Upon successful import, it uses the store. In case of an error, it catches and logs the error.