Blog>
Snippets

Implementing Code Splitting with Redux and ESM

Demonstrate how code splitting can be achieved in a Redux application using dynamic imports with the ECMAScript module system.
// ReduxReducer.js
export const myReducer = (state = {}, action) => {
  switch (action.type) {
    case 'ACTION_TYPE':
      return { ...state, data: action.payload };
    default:
      return state;
  }
};
This file defines a Redux reducer to be dynamically loaded.
// AsyncComponent.js
import React, { useState, useEffect } from 'react';
import { createStore } from 'redux'; 

const AsyncComponent = () => {
  const [reducer, setReducer] = useState(null);
  
  useEffect(() => {
    const loadReducer = async () => {
      // Dynamically importing the reducer module
      const module = await import('./ReduxReducer');
      setReducer(module.myReducer);
    };
    loadReducer();
  }, []);
  
  // Only create the store once the reducer is loaded
  const store = reducer ? createStore(reducer) : null;
  
  return (
    <div>{store ? <span>Store is ready!</span> : <span>Loading...</span>}</div>
  );
};

export default AsyncComponent;
The React component uses dynamic import to asynchronously load the Redux reducer and create a Redux store when it is ready.
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import AsyncComponent from './AsyncComponent';

ReactDOM.render(
  <React.StrictMode>
    <AsyncComponent />
  </React.StrictMode>,
  document.getElementById('root')
);
The entry point file renders the async component which includes the dynamically loaded reducer.