DEV Community

Cover image for Using useSearchParams in Next.js 14
Ferdian Ahmad Rozikin
Ferdian Ahmad Rozikin

Posted on

Using useSearchParams in Next.js 14

Introduction

In modern web application development, managing query strings in URLs is becoming increasingly important, especially when dealing with navigation and search parameters. In Next.js 14, useSearchParams is a hook that allows developers to easily access and manipulate URL search parameters. This article will explain how to use useSearchParams with a complete implementation example in a Next.js 14 application.

What is useSearchParams?

useSearchParams is a hook provided by Next.js for working with search parameters (query parameters) in URLs. This hook is similar to useQueryParams in React Router but is specifically designed for the Next.js ecosystem. With useSearchParams, you can read, modify, and manipulate query strings without reloading the page.

How to Use useSearchParams

To use useSearchParams, you need to import this hook from next/navigation:

import { useSearchParams } from 'next/navigation';
Enter fullscreen mode Exit fullscreen mode

You can then use it within your React component. Below is a complete example of a component that manages search parameters and renders a list of items based on the category selected from the query string.

Creating the CategoryFilter Component
This component will display category filters and manage the category query string in the URL.

import { useSearchParams } from 'next/navigation';

const CategoryFilter = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const category = searchParams.get('category');

  const handleChangeCategory = (newCategory) => {
    const newSearchParams = new URLSearchParams(searchParams);
    newSearchParams.set('category', newCategory);
    setSearchParams(newSearchParams);
  };

  return (
    <div>
      <p>Current Category: {category || 'All'}</p>
      <button onClick={() => handleChangeCategory('technology')}>Technology</button>
      <button onClick={() => handleChangeCategory('health')}>Health</button>
      <button onClick={() => handleChangeCategory('finance')}>Finance</button>
    </div>
  );
};

export default CategoryFilter;
Enter fullscreen mode Exit fullscreen mode

Creating the ItemList Component
This component will display a list of items based on the category retrieved from the query string using useSearchParams.

import { useSearchParams } from 'next/navigation';

const ItemList = () => {
  const [searchParams] = useSearchParams();
  const category = searchParams.get('category');

  const items = [
    { id: 1, name: 'Tech News', category: 'technology' },
    { id: 2, name: 'Health Tips', category: 'health' },
    { id: 3, name: 'Stock Market Update', category: 'finance' },
    { id: 4, name: 'New Gadgets', category: 'technology' },
    { id: 5, name: 'Healthy Recipes', category: 'health' },
  ];

  const filteredItems = category
    ? items.filter(item => item.category === category)
    : items;

  return (
    <div>
      <h2>Items List</h2>
      <ul>
        {filteredItems.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default ItemList;
Enter fullscreen mode Exit fullscreen mode

Combining CategoryFilter and ItemList Components
Here is the main component that combines CategoryFilter and ItemList, allowing users to select a category and see the list of items filtered by that category.

import CategoryFilter from './CategoryFilter';
import ItemList from './ItemList';

const CategoryPage = () => {
  return (
    <div>
      <h1>Category Filter</h1>
      <CategoryFilter />
      <ItemList />
    </div>
  );
};

export default CategoryPage;
Enter fullscreen mode Exit fullscreen mode

Code Explanation

CategoryFilter: This component allows users to select a category and updates the category query string in the URL without reloading the page. When a category is selected, the URL is updated, and the selected category is displayed.

ItemList: This component consumes the category query string and renders a list of items filtered by the selected category. If no category is selected, all items are displayed.
CategoryPage: This component combines the two components above to create a functional category filter page, where users can select a category and view the relevant list of items.

Benefits of Using useSearchParams

Simplifies Navigation: Managing query strings becomes easier without needing direct interaction with window.location.
No Page Reload Required: Changes to the query string do not require a page reload, making the application more responsive.
Strong Integration with Next.js: This hook is specifically designed to work well within the Next.js ecosystem.

Conclusion

useSearchParams in Next.js 14 is a powerful tool for elegantly and efficiently handling query strings in URLs. With this hook, you can easily read and manipulate search parameters in your application, enhancing the user experience. The example provided above demonstrates how you can build a dynamic category filter and display a list of items based on the search parameters present in the URL.

With this approach, you can manage and render dynamic content based on the search parameters in the URL, creating a more interactive and responsive user experience in your Next.js 14 application.

Top comments (0)