Last updated: Apr 6, 2024
Reading timeยท2 min
Use the useSearchParams
hook to programmatically update query params in
React router.
The useSearchParams
hook is used to read and modify the query string in the
URL for the current location.
import React from 'react'; import { useSearchParams, } from 'react-router-dom'; export default function App() { const [searchParams, setSearchParams] = useSearchParams(); const handleClick = () => { setSearchParams({myParam: 'bobby_hadz'}); }; 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.
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.
The useSearchParams hook is used to read and modify the query string in the URL for the current location.
It returns an array containing 2 elements -
const [searchParams, setSearchParams] = useSearchParams()
.
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 remove query parameters using React Router, click on the link and follow the instructions.
If you need to programmatically navigate to a different route with query params,
use the useNavigate
hook instead.
// ๐๏ธ Import useNavigate import {useNavigate} from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // ๐๏ธ Navigate programmatically navigate({pathname: '/about', search: '?site=bobbyhadz&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
.