How to Use useSearchParams Hook in React Router
This article provides a straightforward guide on how to implement and
use the useSearchParams hook from React Router in your
React applications. You will learn how to read, update, and manage query
parameters in the URL using this built-in hook, complete with practical
code examples.
The useSearchParams hook is a feature of
react-router-dom (version 6 and above). It is used to read
and modify the query string in the URL for the current location. It
returns an array of two values: the current location’s search parameters
(as an instance of URLSearchParams) and a function to
update them.
Step 1: Install React Router
To use this hook, ensure you have react-router-dom
installed in your React project.
npm install react-router-domStep 2: Import the Hook
Import useSearchParams from
react-router-dom at the top of your component file.
import { useSearchParams } from 'react-router-dom';Step 3: Implement useSearchParams
The syntax of useSearchParams is highly similar to
React’s standard useState hook.
Here is a complete, practical example of how to implement it to handle a search input:
import React from 'react';
import { useSearchParams } from 'react-router-dom';
function ProductList() {
// Initialize the hook
const [searchParams, setSearchParams] = useSearchParams();
// Read the 'search' parameter from the URL (defaults to empty string if not present)
const searchQuery = searchParams.get('filter') || '';
const handleInputChange = (event) => {
const value = event.target.value;
// Update the URL search parameter
if (value) {
setSearchParams({ filter: value });
} else {
setSearchParams({}); // Clears the parameters if input is empty
}
};
return (
<div style={{ padding: '20px' }}>
<h2>Product Catalog</h2>
<input
type="text"
placeholder="Filter products..."
value={searchQuery}
onChange={handleInputChange}
style={{ padding: '8px', width: '250px' }}
/>
<p>Active Filter: <strong>{searchQuery || 'None'}</strong></p>
</div>
);
}
export default ProductList;Key Methods of the searchParams Object
The first element returned by the hook is a standard standard
JavaScript URLSearchParams object, which grants access to
several helpful methods:
searchParams.get(key): Returns the first value associated with the given search parameter.searchParams.getAll(key): Returns an array of all values associated with a given search parameter (useful for arrays in URLs like?tags=react&tags=node).searchParams.has(key): Returns a boolean indicating whether a specific parameter exists.
Updating Multiple Parameters
When updating the search parameters, passing a new object to the setter function replaces the existing search query entirely. If you want to append or update one parameter while preserving others, you can copy the existing parameters first:
const updateFilters = (newCategory) => {
const currentParams = Object.fromEntries([...searchParams]);
setSearchParams({ ...currentParams, category: newCategory });
};