duxfox-- duxfox-- - 3 months ago 16
React JSX Question

Redux - Number of stores clarification

I've been using redux for a few weeks now, and I've used flux before too, but I want to make sure I use redux the right way. All my research so far has pointed toward having a single store. This is fine, but most explanations and examples discuss a single page application. What happens when an application grows to more than 1 'single-page app'?

For example, a collection of single page applications, each organized as a module folder, each having nothing to do with each other. Is this a case where multiple stores are an option? So each module would have its own store, reducers, etc... Or is it still considered the redux way to have 1 store shared between all the modules?

BTW - by 'single-page app' I don't literally mean 1 page, but a module, which could consist of 1-5 actual pages that share data and other features

Answer

having a single store

This is exactly how Redux works. You have a single store and many actions. Each action, when dispatched, updates the store via reducer.

When you create store, you create a single store:

import { createStore } from 'redux';
import { render } from 'react-dom';

export default render(
  <Provider store={createStore(...)}>
    ...
  </Provider>
, document.getElementById('...'));

The createStore call returns a single store that will then be used by Provider component to pass data from the store to connected components (aka containers).

a collection of single page applications, each organized as a module folder, each having nothing to do with each other.

Each individual part can use its own part of the store. You can divide them using combineReducers function:

import { createStore } from 'redux';
import { render } from 'react-dom';
import moduleA from './reducers/moduleA';
import moduleB from './reducers/moduleB';
import moduleC from './reducers/moduleC';

const store = createStore(combineReducers({
  moduleA,
  moduleB,
  moduleC
});

export default render(
  <Provider store={store}>
    ...
  </Provider>
, document.getElementById('...'));

and have store as object that has as many properties as there are reducers. Each reducer is now responsible for its own part of the state, therefore module. None of reducers, when done correctly, can mutate the part of the state different from the one this reducer is responsible for.

You should take a look at any boilerplate, there are many. For example, erikras/react-redux-universal-hot-example.

Comments