useSearchParams is rarely used but is very useful
Since now many people have used React Hooks, and one of the hooks that are often used is useState
. useState
is always used to maintain state within the component context in React.
Below is an example of using useState:
const [state, setState] = useState('');setState('react');
There is a weakness in using useState, namely the state will return to its original state if the page is refreshed or moved to another page. There are useSearchParams which can be a solution to the above problem, this Hook can be used for not too many states, with 2000 characters, and with a simple value.
As an example
https://test.com/?page=1&limit=10
The URL has several params: page
and limit
. Here we can use useSearchParams
from react router
, react router
can get search params from the above URL.
import { useSearchParams } from "react-router-dom";
const [searchParams, setSearchParams] = useSearchParams();
const page = searchParams.get('page');
setSearchParams({ 'page': '1' });
There’s something that useSearchParams
the code sample above can’t maintain the query string or other params. If you want to store multiple params in your app, what will be very useful are hooks that will allow us to update the state without losing other params. It would also be great if we didn’t have to get the searchParams
object first and then manipulate it. It’s time for us to use useSearchParamsState
Hook:
import { useSearchParams } from "react-router-dom";
export function useSearchParamsState(searchParamName, defaultValue) {
const [searchParams, setSearchParams] = useSearchParams();
const obtainedSearchParam = searchParams.get(searchParamName);
const searchParamsState = obtainedSearchParam ?? defaultValue;
const setSearchParamsState = (newState) => {
const newParams = Object.assign(
{},
[...searchParams.entries()].reduce(
(params, [key, value]) => ({ ...params, [key]: value }),
{}
),
{ [searchParamName]: newState }
);
setSearchParams(newParams);
};
return [searchParamsState, setSearchParamsState];
}
The above hook seems like useState, but stores that state in the URL.
Thank you