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

Fernando Abolafio
Sep 7, 2019 · 3 min read

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 }, “”, newurl);
};
  • setQueryStringValue: updates the query string parameters only for the provided key, keeping the remaining parameters intact.
const setQueryStringValue = ( 
key,
value,
queryString = window.location.search
) => {
const values = qs.parse(queryString);
const newQsValue = qs.stringify({ …values, [key]: value });
setQueryStringWithoutPageReload(`?${newQsValue}`);
};
  • getQueryStringValue: returns the query string value for the provided key.
export const getQueryStringValue = ( 
key,
queryString = window.location.search
) => {
const values = qs.parse(queryString);
return values[key];
};

Writing the hook

All we have to do now is to write our hook:

Breaking it down:

First, we import the hooks useState and useCallback from React and the functions getQueryStringValue and setQueryStringValue we defined before from another file which I called "queryString.js".

Our hook, named useQueryString , receives two parameters:

  • key: the key used to identify our state value in the query string.
  • intialValue: the initial value used if there isn't a value for the provided key among the query string parameter yet.

We initialize our state by checking if there is already a value for the given key in the query string. In case there isn't, we just use the provided intialValue .

We declare a callback function onSetValue wrapped with the useCallback hook to avoid our function to be redefined in every re-render. Once it is called, this function will update the hook state and also the value of the query string with the provided newValue .

Finally, we return from the hook the value and the onSetValue . That's all the consumer of this hook will need to keep its state in sync with the query string.

Controlling the Tabs component with useQueryString

For illustration purpose, we are going to use very simple Tabs components from react-bootstrap. The final result of our app looks like this:

The full implementation is in the following CodeSandbox. You can play around to understand better how it works:

Can we make it better?

Yes, we can. In this tutorial, I described the simplest way of creating this hook. However, It is possible to make it more powerful by extending its functionalities and provide an array of valid values, so you don't end up with non-sense values in your component state. I won't go into details in this post but you can check how it looks like here.

Conclusion

This is my version of using React hooks to sync the component state and the query string. I hope you enjoyed reading this! Please, drop comments here If you have any questions or suggestions on how to improve the code presented.

The Startup

Get smarter at building your thing. Join The Startup’s +724K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store