Design Converter
Education
Last updated on Feb 11, 2025
Last updated on Feb 11, 2025
When working with React Router, managing URL query strings effectively can greatly enhance your app's functionality. The useSearchParams hook, part of React Router DOM, makes this process straightforward.
This blog covers how to work with search parameters, manipulate them using the setSearchParams method, and ensure seamless navigation through query strings in a React application.
Search parameters, often referred to as query strings, are key-value pairs appended to a URL. They help pass information between components without relying on the app's state. In React Router, you can easily manage these parameters using the useSearchParams hook.
For example:
1<https://example.com/page?filter=active&sort=asc>
In this URL, filter and sort are search params that help define how content should be displayed.
The useSearchParams hook is a part of React Router DOM. It provides a tuple with two values: the current searchParams object and a setter function to update it. This hook simplifies handling query strings by allowing you to modify and read search parameters in a React component.
Tuple Structure: useSearchParams returns a tuple containing searchParams and setSearchParams.
Current SearchParams: The first value in the tuple is the current state of search parameters as a URLSearchParams object.
Setter Function: The second value is a function to update search parameters.
To start using useSearchParams, first import it from react-router-dom:
1import { useSearchParams } from 'react-router-dom';
Here’s an example of how to use it in a functional component:
1const MyComponent = () => { 2 const [searchParams, setSearchParams] = useSearchParams(); 3 4 const updateFilter = (filterValue) => { 5 searchParams.set('filter', filterValue); 6 setSearchParams(searchParams); 7 }; 8 9 return ( 10 <div> 11 <button onClick={() => updateFilter('active')}>Set Filter to Active</button> 12 </div> 13 ); 14};
• The useSearchParams hook returns the searchParams object.
• The setter function updates the URL with new parameters.
To manipulate search params, you’ll frequently call methods from the URLSearchParams object, such as .set(), .get(), and .delete(). Each method allows you to modify the parameter values and update the URL accordingly.
1searchParams.set('page', '2'); 2setSearchParams(searchParams);
To retrieve a value from the searchParams object, use the .get() method:
1const currentPage = searchParams.get('page'); 2console.log(currentPage); // Logs '2'
When calling setSearchParams, the URL updates without refreshing the page. This is a core feature of React Router, enabling smooth navigation.
1searchParams.set('filter', 'completed'); 2searchParams.set('sort', 'desc'); 3setSearchParams(searchParams);
If you want to preserve previous search parameters while adding new ones, ensure you merge the new params with the current ones:
1const updateParams = (key, value) => { 2 const newParams = new URLSearchParams(searchParams); 3 newParams.set(key, value); 4 setSearchParams(newParams); 5};
In a paginated React app, search parameters like page help track the current page number.
1const goToNextPage = () => { 2 const currentPage = parseInt(searchParams.get('page') || '1', 10); 3 setSearchParams({ page: currentPage + 1 }); 4};
You can use search params to control filters and sorting options.
1setSearchParams({ filter: 'active', sort: 'asc' });
Although URLSearchParams doesn’t natively support arrays, you can encode arrays as comma-separated strings.
1searchParams.set('tags', 'react,router,hook');
To parse it back into an array:
1const tags = searchParams.get('tags').split(',');
In some cases, you might want to navigate to a new route while preserving certain parameters. React Router’s useNavigate hook works well with useSearchParams.
1const navigate = useNavigate(); 2const handleClick = () => { 3 navigate('/new-page?' + searchParams.toString()); 4};
When using forms, you can capture user input and update search params accordingly.
1const handleFormSubmit = (event) => { 2 event.preventDefault(); 3 const formData = new FormData(event.target); 4 setSearchParams({ search: formData.get('query') }); 5};
Sometimes, search parameters may be undefined or missing. Handle such cases by providing default values.
1const currentPage = searchParams.get('page') || '1';
Replacing vs. Merging: setSearchParams replaces all parameters by default.
Mutable Object: Always create a new URLSearchParams instance when modifying search params.
In React Router, the useSearchParams hook simplifies query string management. By leveraging the setSearchParams method and understanding how to manipulate the URLSearchParams object, you can build more dynamic and user-friendly applications.
• Use useSearchParams to read and update search params.
• Call setSearchParams to modify the URL without refreshing the page.
• Handle common cases like pagination, filtering, and navigation effectively.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.