What we learn from React Router v4 and Redux

xcv58
xcv58’s blog
Published in
2 min readOct 18, 2016

--

We have an internal project using React, Redux, React Router v4, redux-saga, redux-act.

The requirement includes making the entire page state shareable by URL, which means we should put at least six variables in URL. The requirement also breaks the Redux data flow, because we have to either manually change the URL by Redux action or let URL changes manipulate our store.

Our first design is using a dedicated Redux store for URL only. Let other UI components fire action to modify the URL store, then generate new URL and put it into browser’s address bar. The painful story comes because we have to handle the two-way URL: UI Components data sync. Every time the URL changes we have to check whether it’s triggered by UI change or user hit back/forward button. The code becomes worse because we need to handle a bunch of edge cases, even some race conditions.

We end up to give up the idea of putting URL to Redux store. We use React Router to parse URL and manage our UI components/containers. It just works.

I do agree it’s not a Redux way to do things, and it breaks the actions/reducers/store/containers loop. We add an addition loop of URL/containers/components. We use container to manage the data sync between URL and redux store. It’s just a few line of if-else checks to solve all of the sync problems.

Below are lessons we learned:

  1. Don’t duplicate any data unless you have no choice. Please think at least three times before duplicating your data. To sync duplicate data is painful, error prone, and add unnecessary complexity to your codes.
  2. Don’t put too much logic in Redux store, even if you are using powerful redux-saga.
  3. Use declarative programming if possible. React provides an excellent example of declarative programming. Now React Router v4 gives us an impressive Declarative Routing. Declarative programming makes your code cleaner, readable, testable, and modulable.
  4. Don’t try to hook React life cycle unless you understand the side effect very well.

--

--