Understanding The UseParams & UseSearchParams Hooks

Understanding The UseParams & UseSearchParams Hooks

Simplifying URL Handling with UseParams & UseSearchParams in React

Introduction

As a React developer, the react-router-dom is an essential package and a necessary dependency in any React project that requires navigation between routes. The react-router-dom package enables client-side routing in our applications.

NOTE: Client-side routing is what allows your React application to update its URL from a link click without making another request for another document from the server. Instead, your app can immediately render some new UI and make data requests with a fetch to update the page with new information.

Although the useParams and useSearchParams hooks are relatively simple to eliminate in a small project, they are less commonly used compared to the more fundamental hooks such as useState, useEffect, useContext, and useReducer, which are crucial in any React project and cannot be dispensed with easily.

What is the useParams Hook?

This is a hook provided by the React Router library that allows you to extract data from a URL and use it within your React components. This hook makes it easy to access the dynamic URL parameter and use them to display dynamic content based on that URL.

Purpose of useParams hook

The useParams hook helps you extract the dynamic part attached to a URL and returns an object of key/value pairs of the dynamic parameter in a URL. This is usually that part of a URL that helps you navigate to a particular route to display a single item such as displaying a specific user profile, a specific product, or a specific blog post. Let's say for example we have a react component that helps display a single item for a particular product on an e-commerce page.

import * as React from 'react';
import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Routes>
      <Route path="products">
        <Route path=":productsId" element={<ProductsDetailsPage />} />
      </Route>
    </Routes>
  );
}

Accessing dynamic URL parameters

From the code snippet attached, the dynamic part of the URL that we are concerned with is the /:productsId which would be extracted from the full URL path - localhost:3000/products/1.

The productsId which is 1 in the URL is what is returned when we invoke the useParams hook in our react component, but now it doesn't just return it as a string, it is then returned in form of an object.

And to access that dynamic part of this URL, we would have to destructure and grab the productsId, which is the value of the returned object key/value pair that the useParams hook gives us when used within our react functional component.

Example code for extracting dynamic URL parameters with useParams hook

import { useParams } from 'react-router-dom';

function ProductsDetailsPage() {
  const params = useParams()
  const { productsId } = params //NOTE: HERE WE DESTRUCTURE THE PRODUCTSID  

  return <h3>Product ID: {productsId}</h3>;
 }

What is the useSearchParams Hook?

The useSearchParams hook provided by the React Router library helps you manage the information that's included in a URL after the "?" symbol (known as query parameters). It gives react developers an easy interface to read and change the query parameters, without having to worry about the complicated details of parsing and stringifying the data.

Purpose of useSearchParams hook

Unlike the useParams hook which only helps you extract the dynamic part of a URL, on the other hand, the useSearchParams hook allows us to extract the query parameters and also allows us to modify these query parameters in a URL.

The useSearchParams hook simplifies the process of accessing query parameters in a URL within any react functional component. A practical example of its use would be to extract filter criteria from the search section of a URL to dynamically update the displayed content on a web page.

Remember, this is that section of a URL that comes after the question mark(?) symbol, and they are usually used to pass data to the server or filter data on the client side.

Accessing and modifying query string parameters in a URL

Let's say we have this URL: localhost:3000/products?category=all

As stated earlier, the useSearchParams only deals with the query parameter of a URL. In this case, the query parameter is "category" which comes after the question mark(?) symbol with its value equal to "all". And to extract the value of the query parameter in this case, we invoke the useSearchParams hooks and use the get method it provides us.

Example code for using useSearchParams hook to extract query parameters and modify them in the URL

import * as React from 'react';
import { useNavigate, useSearchParams } from "react-router-dom";

function ProductList() {
  let navigate = useNavigate();
  let searchParams = useSearchParams();

 let [category, setCategory] = useState(searchParams.get("category") ||   "all");

  React.useEffect(() => {
   /**LOGIC TO COMPUTE DATA THAT DISPLAYS THE LIST OF PRODUCTS BASED ON ITS CATEGORY**/
  },[category])

  function handleFilter(newCategory) {
    setCategory(newCategory);
    searchParams.set("category", newCategory);
    navigate(`/products?${searchParams.toString()}`
  }

  return (
    <div>
      <h1>Product List</h1>
      <div>
        <button onClick={() => handleFilter("all")}>All</button>
        <button onClick={() => handleFilter("books")}>Books</button>
        <button onClick={() => handleFilter("electronics")}>Electronics</button>
        <button onClick={() => handleFilter("clothing")}>Clothing</button>
      </div>
      <ul>
        {/* code to display the filtered products goes here */}
      </ul>
    </div>
  );
}

In this example, the useNavigate hook from the react-router-dom library is used to navigate us to a new route anytime a button is clicked, and the button receives an argument that determines the route we would navigate to.

The category state is initialized with the current value of the category query parameter, and the setCategory update function is used to modify the category state whenever the user selects a new filter category by clicking on a button.

Assuming the user clicks the button "electronics", The handeFilter function is called which then modifies the category query parameter using the set method of the useSearchParams object, and then updates the URL using the navigate function provided by the useNavigate hook that automatically updates the URL to localhost:3000/products?category=electronics.

This is just a simple example of how you can use the useSearchParams hook to modify query parameters and update the URL dynamically in any React application. You can build upon this example to create more complex URL-driven components in your projects!

Conclusion

With all being said, the useParams and useSearchParams hooks provided by the React Router library are essential tools for React developers to extract and manipulate data from a URL.

The useParams hook is used to extract the dynamic part of a URL and returns the data as key/value pairs, while the useSearchParams hook allows you to access and modify the query parameters in a URL.

These hooks provide a convenient and efficient way for developers to navigate between routes and access the data from a URL within React components, making it an essential tool for any React project that requires navigation.

Hope, You liked this article and it was helpful to you. If I missed something or made a mistake, feel free to comment.

Want to stay connected? Feel free to follow and reach out to me on either of these platforms LinkedIn | Twitter | Github.