How to sync Redux state and url query params

Anton picture Anton · Apr 13, 2016 · Viewed 41.2k times · Source

I have a web page with a search panel. Search panel has several input fields: id, size, ...

What I want is when user set search values (for example: id=123 and size=45) and press a search button:

  1. searchState in Redux reducer should be updated with new search values (id=123 and size=45)
  2. URL should be changed to "http://mydomain/home?id=123&size=45"

And on the other hand if the user changes URL to http://mydomain/home?id=111&size=22 then:

  1. searchState in reducer should be changed with new search values (id=111 and size=22)
  2. UI search panel inputs should be updated with new values (id=111 and size=22)

How to reach with goal? What router should I use (react-router, redux-router, react-router-redux ot other)?

Answer

Dan Abramov picture Dan Abramov · Apr 16, 2016

I would suggest just using React Router directly and not keeping searchState in Redux. React Router will inject URL parameters into your components, and you can use them in mapStateToProps(state, ownProps) to calculate the final props.

If you really want to see route changes as actions, you can use react-router-redux for two-way syncing, but it won’t give you the params in the state—just the current location. The only use case for it if you want to record and replay actions, and have the URL bar update as you replay them.

It is by no means required—in most cases, just using React Router directly is enough.