React-State Management using URL
Hi Reader ,
Today let's look at on how to store the state of our pages in the URL and those can be used to increase the Performance and to maintain the state even if the page is Reloaded.
Why we need to put our state in the URL ?
In the applications we build , we need to maintain a particular state which we might show it to our users or we may use it to make API calls , In either way we need something to put our state and make sure it's available whenever we revisit that page in the particular scenario
When I say scenario it means the same page may have multiple states , I hope I confused you as much as I can , let us see it with an example, to make you clear on what the word scenario Implies here
Now I am going to add some state to the page
I have entered some value and clicked Apply , if you notice , there is a search string added to the URL of the page and that is our state and then now I am going select some other options and click Apply button
Now a new search string is added to the URL which means our new state has been added to the state
now we can make unique API calls for each state , without depending on local storage to store them or any other state management library and if the data which has to be shown is not so big we can also store the Data which comes from the backend and show it to our users , this can save many API calls and will increase the performance of our application
You can navigate from one page to another or remain in the same page using browser's back button still you can maintain the state , I think this is the beauty of this kind of state management
Ok enough of confusing you let's look at the code and how it can be achieved , I have written a simple custom hook to make this logic as a reusable one , hope you can also use it in your applications without much changes
领英推荐
How to do it ?
I have added an external library to the parse the value which you can avoid , if you want
"query-string": "^8.1.0",
and you can also add a library to make it more elegant if you want and that is
"base64url": "^3.0.0",
these two are up to you
Now let's see the required code
import { useState, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import queryString from 'query-string'
const useURLStore = () => {
const [queryPara, setQueryPara] = useState<string>("")
const [searchData, setSearchData] = useState<any>(null)
const location = useLocation();
const navigate = useNavigate();
const setURLString = (searchFilter: any) => {
const val = window.btoa(queryString.stringify(searchFilter))
setQueryPara(val);
}
useEffect(() => {
if (queryPara !== "" && queryPara !== null) {
navigate(`${location.pathname}?search=${queryPara}`)
}
}, [queryPara])
const getUrlString = () => {
if (location.search !== "") {
let urlStr = location.search.slice(8);
if (urlStr) {
setSearchData(queryString.parse(window.atob(urlStr)))
}
}
}
useEffect(() => {
getUrlString()
}, [location.search])
useEffect(() => {
getUrlString()
}, [])
return {
setURLString,
getUrlString,
searchData,
location,
navigate,
setSearchData,
}
}
export default useURLStore
Page code
const [searchText, setSearchText] = useState<string>("")
const [name, setName] = useState<string>("")
const [section, setSection] = useState<string>("")
const { setURLString, searchData, } = useURLStore()
const applyHandler = () => {
const filter = { searchText, name, section }
setURLString(filter)
}
useEffect(() => {
if (searchData && location.search) {
setName(searchData?.name)
setSearchText(searchData?.searchText)
setSection(searchData?.section)
}
}, [location.search, searchData])
You can try this code as it is in your React JS Application and that will help you I guess
Since I would like keep this short , not explaining much about the code , If you just take a look at it , hope you will get it
Anyway , I did not write much lately , will try to contribute something better in the coming days
Thanks for your time ,
VMkrishna