I still don’t have much experience with Redux.
But I have a situation at work where we will have an application with several modules.
Each module will have its own store
.
I’m not able to merge all these stores into one store and then create a general store for all the project.
Could you tell me how can i do this?
import { combineReducers, createStore } from "redux"; const rootReducer1 = combineReducers({ reducerA: reducerA, reducerB: reducerB, reducerC: reducerC }); export const store1 = createStore(rootReducer1); /*****/ import { combineReducers, createStore } from "redux"; const rootReducer2 = combineReducers({ reducerD: reducerD, reducerE: reducerE, reducerF: reducerF }); export const store2 = createStore(rootReducer2); /*****/ import { combineReducers, createStore } from "redux"; import store1 from "../modules/module1/reducers"; import store2 from "../modules/module2/reducers"; const rootReducer = combineReducers({ store1: store1, store2: store2 }); export const store = createStore(rootReducer); /*****/ import { StrictMode } from "react"; import ReactDOM from "react-dom"; import { Provider as ReduxProvider } from "react-redux"; import { store } from "./store"; import App from "./App"; const rootElement = document.getElementById("root"); ReactDOM.render( <StrictMode> <ReduxProvider store={store}> <App /> </ReduxProvider> </StrictMode>, rootElement );
I created a test project in codesandbox.io just to demonstrate the idea of what the project will be like.
Advertisement
Answer
combineReducers(reducers) helper function turns an object whose values are different reducing functions into a single reducing function. It can’t combine multiple stores.
Besides, the best practice is Only One Redux Store Per App
A standard Redux application should only have a single Redux store instance, which will be used by the whole application
You can have each module act as a first-level slice on the redux state tree like this:
store.js
:
// module 1 const rootReducer1 = combineReducers({ reducerA: reducerA, reducerB: reducerB, reducerC: reducerC }); // module 2 const rootReducer2 = combineReducers({ reducerD: reducerD, reducerE: reducerE, reducerF: reducerF }); // App const rootReducer = combineReducers({ module1: rootReducer1, module2: rootReducer2 }); export const store = createStore(rootReducer);
The structure of the redux state tree will be like this:
{ module1: { reducerA: {}, reducerB: {}, reducerC: {} }, module2: { reducerD: {}, reducerE: {}, reducerF: {} }, }
If the module becomes large in the future, you can split it into a separate application with its own redux store.