Sept 16 2023
Managing React state with URL Params
react
useStateParam, managing react state with URL Params
Table of Contents
Introduction
By the end of this post, you will know how to make a custom useStateParam
hook to synchronise React state with the URL search parameters and why this is useful.
Advantages
- people viewing the page can save the URL with non-default
state
for future visits - people can share the exact URL with other people or themselves
- state and UI is restored after a page reload
- people can use the window history to go back and forward
useStateParam hook
The custom useStateParam hook is used to store store useState
state in the page url.
import { useEffect, useState } from "react";
export function useStateParam(initialValue:any=null,param:string){
const [value,setValue]=useState(initialValue)
//get from query params
useEffect(()=>{
let params = new URLSearchParams(window.location.search)
let newValue = params.get(param)
if (newValue){
setValue(newValue)
}
},[])
// update query params
useEffect(()=>{
const params = new URLSearchParams(window.location.search)
params.set(param,value)
const newUrl = `${window.location.origin}${window.location.pathname}?${params.toString()}`
window.history.pushState(null,"",newUrl)
},[value])
return [value,setValue]
}
Conclusion
Now you know how to make a custom useStateParam
hook to put the component state in the URL params in React. Thank you for reading.
You have reached the end of this post. Thank you for reading!