Blog>
Snippets

Integrating State Management with Code-Split Components

Discuss how to integrate state management solutions (e.g., Redux or Context API) with code-split components to maintain application state cohesively.
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';

const store = configureStore({ reducer: rootReducer });

export default store;
This code snippet sets up a Redux store using Redux Toolkit. 'configureStore' simplifies store configuration, and 'rootReducer' is a combination of all reducers in the application.
import { Provider } from 'react-redux';
import store from './store';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
This snippet wraps the application with the Redux 'Provider', passing the store as a prop. This enables all components in the app hierarchy to access the Redux store.
import loadable from '@loadable/component';

const LazyComponent = loadable(() => import('./LazyComponent'), {fallback: <div>Loading...</div>});
Here, the '@loadable/component' library is used to create a code-split component, 'LazyComponent'. The 'fallback' prop defines what is displayed while the component is being loaded.
import { useSelector } from 'react-redux';

const LazyComponent = () => {
  const data = useSelector((state) => state.data);
  return <div>{data}</div>;
};

export default LazyComponent;
Inside a lazy-loaded component, 'useSelector' from 'react-redux' is used to access Redux state. This maintains cohesive state management across both eagerly and lazily loaded components.