Using use-query-params in a React Application
Why use-query-params?
When you want to store your state in the URL, you can use the use-query-params
library.
This is useful when you want to make your application shareable by providing a URL with the state or when you want to save the state of your application in the browser history.
Step 1 - Install the library and wrap your application routes with the QueryParamProvider
.
npm install use-query-params
import { QueryParamProvider } from 'use-query-params';
function App() {
return (
<QueryParamProvider>
<Routes>
<Route path="/" element={<App />}>
</Routes>
</QueryParamProvider>
);
}
Step 2 - Use the library
import { useQueryParam, NumberParam, StringParam } from "use-query-params";
function App() {
const [count, setCount] = useQueryParam("count", NumberParam);
const [name, setName] = useQueryParam("name", StringParam);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount((prevCount) => prevCount + 1)}>
Increment
</button>
<h1>Name: {name}</h1>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}
Step 3 - Use the state
Now you can use the count
and name
state in your application. The state will be stored in the URL and updated when the URL changes.
Furthermore
If you want to use the state in a specific component, you can use the useQueryParam
hook in that component. This way, you can have different states for different components in your application.
import { useQueryParam, NumberParam } from "use-query-params";
function Counter() {
const [count, setCount] = useQueryParam("count", NumberParam);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount((prevCount) => prevCount + 1)}>
Increment
</button>
</div>
);
}
Conclusion
Using the use-query-params
library in your React application is a great way to store your state in the URL and share it with others. It is easy to use and provides a simple way to manage the state of your application. Give it a try in your next project!