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.
React is all about state management. Most common state stores are:
- Components’ state
- 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:
- Visibility of components: when you need to show and hide popups, tabs, sliding panes etc.
- Lists’ or tables’ paging! Imagine you can easily provide link to specific page of list or table. For example: “/users?page=2&itemsPerPage=10”.
- 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:
- You can always provide direct link to the opened pane, popup or tab like “http://example.com/user/111/?showEditPaymentInfo=1”
- 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.
- 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:):