using URLSearchParams for Query String in ReactJs

What is a query string?

A Query string is a portion of the URL where data is sent across the application to the server. e.g

https://localhost:3000/products?page=1&category=music

How do we write query string

URLs are stateless; they are not meant to transfer state between or around your application.

https://localhost:3000/products

URL can be followed with a query string and the first string is written

https://localhost:3000/products?page=1
#query string -> ?page=1
#data-> page=1

the key-value pair represent the data, where the first string is the key(variable name) and the second is the value. if there are more data to be transferred we add them preceded with an ampersand "&"

https://localhost:3000/products?page=1&category=music
#query string -> ?page=1&category=music
#data -> page=1  and category=music

How do we use query string in a React App

getting the data from a query string looks quite easy, understanding how the string looks like a basic javascript approach using the split array method would be...

const querystring=?page=1&category=music
const page=querystring.split("=")[0]

The cons of this approach:

  • we have to force the user to input the string like "?page=1&category=music"
  • if it goes otherwise like "?category=music&page=1" our app breaks.

Another better approach is using the URLSearchParams window object

Using URLSearchParams

const qString = window.location.search //?page=1&category=music
const searchParams= new URLSearchParams(qString)
const page = searchParams.get("page")
const category= searchParams.get("category")

we can make this better by turning it into custom hooks

function useQuery() {
  const { search } = window.location;

  return React.useMemo(() => new URLSearchParams(search), [search]);
}

function App(){
const queryString = useQuery()
const page = queryString.get("page")
const category = queryString.get("category")
return <div>...</div>
}

Thanks for reading, follow me for more posts.