React-State Management using URL

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

Initial State of the Application

Now I am going to add some state to the page

Scenario - 1

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

Scenario-2


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


要查看或添加评论,请登录

Vijayamuralikrishna J的更多文章

  • Closure on Hardware

    Closure on Hardware

    Hello Human, Today, I thought about discussing the concept of closure. Let's start with our usual question: What is a…

  • What is Proxy in Javascript ?

    What is Proxy in Javascript ?

    Hi Everyone , Today let's discuss about Proxy in JavaScript and how we can use them in our code. The very first basic…

  • Infinite Scroll Using Monad

    Infinite Scroll Using Monad

    Hi folks , Today I thought about discussing with you all about a code which was written with a lot of side effects and…

  • Type "any"- useful or useless?

    Type "any"- useful or useless?

    Hi folks , It's been sometime , did not write much lately and today I thought to write about type "any" and it's going…

  • Interface in Typescript

    Interface in Typescript

    Hi Folks , Today let's a take a look at Interface in typescript , from the word interface we can understand that we are…

    1 条评论
  • Types in Typescript

    Types in Typescript

    Hi all , As I said in my last article , will write about Typescript in my coming articles ,This is article belongs to…

  • Typescript- Why we must use it in our JS projects ?

    Typescript- Why we must use it in our JS projects ?

    Hi folks , Today I have decided to discuss about TypeScript with you all , When I started to write my applications with…

  • Recursion - Basic Explanation

    Recursion - Basic Explanation

    Hi folks , Today I thought to write about Recursion, a powerful functional programming concept First, let's see the…

  • Play With Pics - Just a CANVAS

    Play With Pics - Just a CANVAS

    Hi Folks , Today I thought of sharing a simple application with you all , I just made this application to exhibit that,…

  • Scope Of React-Testing

    Scope Of React-Testing

    Hi folks, If you are a React developer then probably you will be writing test cases for your apps using jest and…

社区洞察

其他会员也浏览了