Synchronizing query string state with React custom hooks

Andy Beers
Developing Koan
Published in
1 min readNov 10, 2021

Here’s a custom React hook to keep application state in sync with the location query string.

Note that this hook depends on react, qs, and react-router-dom packages, which you’ll need to install separately.

Examples

Let’s imagine that our app contains content filters and a modal which might be open or closed, and we want these values to be reflected in the url query string so that users can deep link to the app in various states. Here we’ll demonstrate a component that uses the useQueryStringSync hook to keep its internal state in sync with the query string.

If you have a component that only needs to keep track of a single query string property, you can use useQueryStringSingleFieldSync. Here, let’s imagine that we have a component which wants to track the open state of a welcome modal via the query string property modalOpen=true.

--

--

Andy Beers
Developing Koan

Web developer, fruity coffee lover, mushroom hater