Search Params and Use Location

When it comes to React applications, URLs can be quite a strong tool to use when it comes to handling data and user interaction. Whatever the information extracted from URl will be important for building dynamic and quick responsive experiences. Today I walk you through one of the most useful hooks from React Router DOM like useSearchParams and useLocation which makes our Dev Life easier to deal with URL based data in our React components.

Understanding Query Strings and URL Parameters

In general, a URL is constructed as of three parts:

  • Protocol (https://): Determines how the communication should be accomplished.
  • Domain Name (e.g., www. example. com): Hosts the content on a server.
  • Path & Query String (e.g., /products? category=electronics&color=blue)

    • The path (/products) informs where the resource is located in the domain.
    • The query string (?category=electronics&color=blue) follows a ? symbol and consists of key-value pairs separated by &. These key-value pairs hold additional data that can be used by the application.

useSearchParams

useSearchParams is a hook that can be used to extract the query parameters from the URL of the current webpage. Query parameters are the parameters that are placed after the ‘?’ symbol consisting of the parameter name and parameter value.

The method is not limited to reading query parameters, it also allows for modifying them, which is useful for making changes to the URL without refreshing the webpage. Those components that have useSearchParams will be re-rendered when the state of query parameters change, which is valuable for creating real-time responsive UIs to the state of URLs.

useSearchParams is a hook which makes playing with search params easier Returns an array with 2 elements:

const [searchParams, setSearchParams] = useSearchParams();
Enter fullscreen mode
Exit fullscreen mode
  • searchParams: An object of the current query string parameters servicing as key-value uses.
  • setQuerySearch: This is a function that helps you update the parameters inferred in the URL.

Here’s an example of using useSearchParams:

import { useSearchParams } from 'react-router-dom'; function ProductList() { const [searchParams, setSearchParams] = useSearchParams(); const category = searchParams.get('category'); const color = searchParams.get('color'); // Logic to filter products based on category and color return ( <div> <h1>Products</h1>
 <p>Showing products for category: {category}, color: {color}</p>
 {/* ... */} </div>
 );
} 
Enter fullscreen mode
Exit fullscreen mode

In this example:

  • We add useSearchParams from react-router-dom.
  • The useSearchParams hook gets the current search params (searchParams) and a function to update the search params (setSearchParams)
  • We use searchParams. get('category') && searchParams. color') to get values to specific query string parameters.
  • The component can now both filter the products or display information, respectively, based on the parameters.

Updating the Query String
To update the query string we call the setSearchParams function, it accepts an object with new key-value pairs for the query string. We can even remove parameters by passing their value as undefined.

setSearchParams({ category: 'electronics', color: undefined }); // Updates category, removes color
Enter fullscreen mode
Exit fullscreen mode

useLocation

The useLocation hook in React Router is used to return the current location of a React component. TheuseLocation() returns the current location as an object and comes with props such as

The useSearchParams is perfect for the new React Router, but useLocation is still useful for working with URLs in older versions or for getting the entire location object.

It is used to return the current location of a React component. It returns the current location as an object and comes with props such as:

  • pathname: A string representing the path of the URL (e.g., /about).
  • search: A string representing the query parameters (e.g., ?name=John).
  • hash: A string representing the URL hash (e.g., #section1).
  • state: An object representing the state that was passed when navigating to this location (e.g., { from: ‘/home’ }).

Here’s an example using useLocation:

import { useLocation } from 'react-router-dom'; function ProductDetails() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); const productId = searchParams.get('id'); // Logic to fetch product details based on productId return ( <div> <h2>Current Location</h2>
 <p>Pathname: {location.pathname}</p>
 <p>Search: {location.search}</p>
 <p>Hash: {location.hash}</p>
 <p>State: {location.state ? JSON.stringify(location.state) : 'No state'}</p>
 </div>
 );
} 
Enter fullscreen mode
Exit fullscreen mode

In this example:

  • We import useLocation from react-router-dom.
  • The useLocation hook retrieves the entire location object.
  • We create a URLSearchParams object from the location.search property to access individual parameters.

Choosing Between useSearchParams and useLocation:

  • Use useSearchParams for shorter code and the new style of working with query string parameters .
  • Use useLocation if you need the entire location object.

Conclusion

With useSearchParams and useLocation we can take full advantage of the power of URLs in our React apps. We can create dynamic and friendly experiences that respond and adapt to the data we encode in the URL.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top