How to Update useSearchParams Hook in React
The useSearchParams hook from React Router is the
standard tool for reading and modifying the query string in a web
browser’s URL. This article explains how to import and use the hook, how
to update a single query parameter while preserving others, and how to
reset or delete parameters. By the end of this guide, you will know how
to keep your React application’s state perfectly synchronized with the
URL.
Getting Started with useSearchParams
To manage query parameters, you must first import the
useSearchParams hook from react-router-dom. It
functions similarly to React’s native useState hook,
returning an array with two elements: the current query parameters (as
an instance of URLSearchParams) and a function to update
them.
import { useSearchParams } from 'react-router-dom';
function MyComponent() {
const [searchParams, setSearchParams] = useSearchParams();
// Read a parameter
const query = searchParams.get('query');
}Overwriting All Query Parameters
The simplest way to update the URL parameters is to pass a plain
object to the setSearchParams updater function. This method
will overwrite all existing query parameters with the new ones you
provide.
const handleSearch = (searchTerm) => {
// This replaces all current parameters with ?search=searchTerm
setSearchParams({ search: searchTerm });
};Updating Specific Parameters (Preserving Others)
If you want to update one specific parameter without deleting the other parameters already present in the URL, you must copy the existing parameters first.
To do this safely in React, instantiate a new
URLSearchParams object using the current
searchParams, modify it, and pass it to the updater
function.
const updateTopicFilter = (newTopic) => {
// Create a new URLSearchParams instance from the existing one
const newParams = new URLSearchParams(searchParams);
// Set or update the specific parameter
newParams.set('topic', newTopic);
// Update the URL state
setSearchParams(newParams);
};Deleting a Query Parameter
To remove a specific parameter from the URL completely while keeping
the rest, use the .delete() method on the
URLSearchParams instance before updating.
const removeTopicFilter = () => {
const newParams = new URLSearchParams(searchParams);
// Remove the 'topic' key from the query string
newParams.delete('topic');
setSearchParams(newParams);
};Controlling Navigation Behavior (Replace vs. Push)
By default, calling setSearchParams pushes a new entry
onto the browser’s history stack. If you want to update the URL without
adding a new step to the user’s browser back-history, you can pass an
options object as a second argument with replace: true.
setSearchParams(newParams, { replace: true });