React + Redux + Router - should I use one state/store for all pages/components?
Asked Answered
S

1

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

Strong answered 8/5, 2016 at 6:25 Comment(0)
I
3

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.

Ignorant answered 8/5, 2016 at 8:8 Comment(4)
Ok. Isn't it kind of an hackie solution? I wonder if there is a cleaner solution for that...Strong
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 itKaryotin
@Karyotin Thanks, I heard about it, will take a look !Strong
@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.Ignorant

© 2022 - 2024 — McMap. All rights reserved.