One practical application of query parameters is to store values from a user’s search.

Using React Router to Update Query Parameters

When a user enters a query into a search bar, you should store that query in the URL. For example, if a user searched a list of blogs for posts in the “react” category, the updated URL should look like this: /posts?tag=react.

React provides the useSearchParams hook that helps you read or update query strings.

To get started, create a search bar in App.js.

Remember to follow best practices when using React to get the most out of them.

Next, install React router and add routing to your application. This is a must for the useSearchParams hook to work.

Now you can save the queries in the URL as the user types by modifying the handleChange() function.

Getting the Query Values From the URL

You can get a single query value using searchParams.get() and passing in the query parameter’s name.

To get all the query parameters, use searchParams.entries().

This method returns an iterator you can iterate using key/value pairs.

The key/value pairs are in the order they appear in the URL.

Use Query Parameters to Improve Shareability of Search Results

The useSearchParams hook is great for storing search values or any other data as query parameters in a URL.

You can also keep track of search values with the useState hook, but storing them in a query parameter means that people can share them via the URL.