Browser location as a store for react.js apps

I’d like to share some little hack, that simplifies UI state management using browser location and react-router.

Dmitry Dushkin
Feb 8, 2017 · 1 min read

React is all about state management. Most common state stores are:

  1. Components’ state
  2. External state management library like redux, mobx or apollo-react

These stores have quite certain use cases, but I found superfluous to use them for such often use cases:

  1. Visibility of components: when you need to show and hide popups, tabs, sliding panes etc.
  2. Lists’ or tables’ paging! Imagine you can easily provide link to specific page of list or table. For example: “/users?page=2&itemsPerPage=10”.
  3. Select rendered component based on query value.

I’ve found very useful using browser location as a store for dealing with these cases. Here are advantages of using browser location as store over others:

  1. You can always provide direct link to the opened pane, popup or tab like “http://example.com/user/111/?showEditPaymentInfo=1”
  2. Advantage of using browser location over component’s state is that you can write “functional (or pure, stateless) component”. Here you can read why it’s better to write functional components over statefull.
  3. Advantage of using browser location over redux (and similar) is that you just write less code. ;)

Here is an example of react-router utility functions that implement this pattern and use case.

Utility functions (these 19 lines do not worth npm package, so it’s a gist:):

Example usage:

Dmitry Dushkin

Written by

Front-end @ Yandex

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade