8

I am using React + Redux, and after reading about react-router-redux and redux-router, and after reading Dan Abramov's answer, I decided to use "vanilla" react-router (I don't care about time travel etc. at this point).

The only open question left is how to handle state across different routes. Each route sub-tree can be a different and independent section in my application (especially when it become bigger). Is it still a good practice to have one store to handle all routes/ pages? Shouldn't I (at least) have a different store/state for each main route path?

I think routes should be some kind of stateless and independent, meaning that if I go directly to one of my links, it should work, and won't be aware of other sibling routes. Should I reflect it to my store?

Edit

After some more thinking, I guess that using different reducers + "CombineReducers" will do the trick. The only thing left to for me to verify is that state of former routes does not persist while navigating

Community
  • 1
  • 1
Yaniv Efraim
  • 6,200
  • 6
  • 48
  • 92

1 Answers1

2

On of the possible solutions to verify that state of former routes does not persist:

Top level components in each route are mounting and unmounting when user navigates between pages. You can use their lifecycle methods to send any redux events to clean your state.

For example send CLEAN_STATE from componentWillUnmount. You should catch this event in your top level reducer end return initial state from it. To do it you can manually call all nested reducers with undefined as a state parameter. In that case each reducer will return it's initial state.

trashgenerator
  • 431
  • 3
  • 7
  • 1
    Ok. Isn't it kind of an hackie solution? I wonder if there is a cleaner solution for that... – Yaniv Efraim May 08 '16 at 09:34
  • 1
    Hi just another tip. Take a look at code splitting within webpack. An awesome kit that does what you describe is redux starter kit. Might be worth looking into it as well just to get an idea of a possible way to do it – Deep May 08 '16 at 12:24
  • @Deep Thanks, I heard about it, will take a look ! – Yaniv Efraim May 08 '16 at 19:30
  • 1
    @YanivEfraim I don't like this solution either but seems it is quite "official" way. Also you can catch "@@reduxReactRouter/routerDidChange" event raised by redux-router in your reducers but there could be (or not) some problems if you are using async loading of components. I'm not sure, didn't try it yet. – trashgenerator May 11 '16 at 17:46