Using URL state with searchParams helps keep track of information in the web address. This makes it easy to share or save the current page view.
0
0
URL state with searchParams in NextJS
Introduction
You want to remember user choices like filters or sorting on a list page.
You want users to share a link that opens the page with the same settings.
You want to keep the page state after refreshing or navigating back.
You want to read values from the URL to load specific content dynamically.
Syntax
NextJS
import { useSearchParams } from 'next/navigation'; const searchParams = useSearchParams(); const value = searchParams.get('key');
useSearchParams is a React hook from Next.js App Router to read URL query parameters.
It returns a URLSearchParams object to get values by key.
Examples
Get the value of the
page parameter from the URL.NextJS
const searchParams = useSearchParams(); const page = searchParams.get('page');
Get
filter parameter or use all if not present.NextJS
const searchParams = useSearchParams(); const filter = searchParams.get('filter') || 'all';
Get the search term from the URL parameter
q.NextJS
const searchParams = useSearchParams(); const searchTerm = searchParams.get('q');
Sample Program
This component reads the query parameter from the URL and shows it on the page. If no query is in the URL, it shows an empty string.
NextJS
'use client'; import React from 'react'; import { useSearchParams } from 'next/navigation'; export default function SearchPage() { const searchParams = useSearchParams(); const query = searchParams.get('query') || ''; return ( <main> <h1>Search Page</h1> <p>Showing results for: <strong>{query}</strong></p> </main> ); }
OutputSuccess
Important Notes
Changing searchParams does not automatically update the component. You need to navigate or refresh to see changes.
Use Next.js navigation methods to update URL parameters and keep UI in sync.
Summary
URL state with searchParams lets you read query parameters from the URL easily.
This helps keep the page state shareable and reloadable.
Use useSearchParams hook in Next.js App Router to access these values.