Synchronizing query string state with React custom hooks
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
.