funerr funerr - 17 days ago 6
Javascript Question

React Native & Redux should I have a Store per Scene/Route?

I am using

react-native-router-flux
to manage navigation in my app. I wanted to know if I should create a store for each scene or should I only create one (and how?)

Right now it looks like this:

App.js

<Router>
<Scene key="root">
<Scene key="mainScene" component={MainScene} title="MainScene" initial={true} />
<Scene key="secondScene" component={SecondScene} title="SecondScene" />
</Scene>
</Router>


MainScene.js

<Provider store={store}>
<MainConnectedComponent/>
</Provider>


SecondScene.js

<Provider store={store}>
<SecondConnectedComponent/>
</Provider>


I read somewhere that redux likes only one store, but I don't know how to make that possible with this kind of navigation that separates the app to different parts.

Answer

You use only one store, but you separate the reducers.

import { createStore, combineReducers } from 'redux';

const mainSceneReducer = (state, action) => {
    ...
};

const secondSceneReducer = (state, action) => {
    ...
};

const store = createStore(
    combineReducers({
        mainSceneReducer,
        secondSceneReducer
    });
);

Update: Now about the router, you would put your Provider around your main Router, and remove it from mainScene.js and secondScene.js:

<Provider store={store}>
 <Router>
    <Scene key="root">
      <Scene key="mainScene" component={MainScene} title="MainScene" initial={true} />
      <Scene key="secondScene" component={SecondScene} title="SecondScene" />
    </Scene>
 </Router>
</Provider>

Related SO question: redux-multiple-stores-why-not

Comments