Using React Hooks to sync your component state and the URL Query string

Fernando Abolafio
The Startup
Published in
3 min readSep 7, 2019

--

Many times we want to control parts of our app by modifying the query string parameters. Learn how you can do it by using React hooks.

To illustrate that we're going to use a simple Tabs component. The idea is:
once the selected tab changes, the query string parameters are updated accordingly. In the same way, if you load your component with a valid query parameter in place, the component will initialize its state accordingly.

The query string modifies as the selected tab is modified

Manipulating the Query string

First, we're going to define a few handfull functions to manipulate the query string. We will use the library query-string to helps us achieve that.

  • setQueryStringWhithoutPageReload: replaces the current query string value with the new provided value without triggering a page refresh.
const setQueryStringWithoutPageReload = qsValue => { 
const newurl = window.location.protocol + “//” +
window.location.host +
window.location.pathname +
qsValue;

window.history.pushState({ path: newurl }, “”…

--

--

Fernando Abolafio
The Startup

Programmer — Modeling Revenue in code @GrowblocksHQ — Writing about Web Dev/React/Remix/NextJs — Software Architecture