Programmatically update query params in React router

avatar

Borislav Hadzhiev

Last updated: Apr 21, 2022

banner

Check out my new book

Programmatically update query params in React router #

Use the useSearchParams hook to programmatically update query params in React router, e.g. setSearchParams({query: 'myValue'}). The useSearchParams hook is used to read and modify the query string in the URL for the current location.

App.js
import React from 'react'; import { useSearchParams, } from 'react-router-dom'; export default function App() { const [searchParams, setSearchParams] = useSearchParams(); const handleClick = () => { setSearchParams({myParam: 'hello_world'}); }; const handleChange = event => { setSearchParams({query: event.target.value}); }; console.log(searchParams.get('myParam')); console.log(searchParams.get('query')); return ( <div> <button onClick={handleClick}>Update Query params</button> <input id="search" onChange={handleChange} /> </div> ); }

You have to make sure you have wrapped your App with a Router component in your index.js file in order to use any of the react router hooks.

index.js
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // 👇️ wrap App in Router root.render( <Router> <App /> </Router> );

The code snippet shows how to update the query params of a route on button click and when an input field is changed.

react update query params

The useSearchParams hook is used to read an modify the query string in the URL for the current location.

It returns an array containing 2 elements - const [searchParams, setSearchParams] = useSearchParams().

The first element is an object that we can use the get the value of a query parameter and the second is a function that takes an object of key-value pairs to which it sets the query params.

The setSearchParams function works like the navigate function from the useNavigate hook, but only for the search portion of the URL.

If you need to programmatically navigate to a different route with query params, use the useNavigate hook instead.

App.js
// 👇️ import useNavigate import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // 👇️ navigate programmatically navigate({pathname: '/about', search: '?query=abc&page=25'}); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }

We passed an object to the navigate function. Notice that the search property is a complete query string.

When the user clicks on the button, they would navigate to /about?query=abc&page=25.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.