Bird
Raised Fist0
NextJSframework~20 mins

URL state with searchParams in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
URL State Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does the component update URL searchParams?

Consider a Next.js component that updates the URL's searchParams when a user selects a filter. What happens when the user selects a new filter?

NextJS
import { useSearchParams, useRouter } from 'next/navigation';
import { useState } from 'react';

export default function FilterComponent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [filter, setFilter] = useState(searchParams.get('filter') || 'all');

  function onChangeFilter(newFilter) {
    setFilter(newFilter);
    const params = new URLSearchParams(searchParams.toString());
    params.set('filter', newFilter);
    router.replace(`?${params.toString()}`);
  }

  return (
    <select value={filter} onChange={e => onChangeFilter(e.target.value)} aria-label="Select filter">
      <option value="all">All</option>
      <option value="active">Active</option>
      <option value="completed">Completed</option>
    </select>
  );
}
AThe URL's searchParams update only after a manual page refresh.
BThe URL's searchParams update but cause a full page reload, losing component state.
CThe component state updates but the URL's searchParams remain unchanged.
DThe URL's searchParams update with the new filter value without a page reload, and the component state updates accordingly.
Attempts:
2 left
💡 Hint

Think about how router.replace works in Next.js App Router.

📝 Syntax
intermediate
1:30remaining
Identify the correct way to read searchParams in a Next.js client component

Which code snippet correctly reads the 'page' parameter from the URL searchParams inside a Next.js client component?

Aconst page = new URL(window.location).searchParams.page;
Bconst searchParams = useSearchParams(); const page = searchParams.get('page');
Cconst page = useRouter().query.page;
Dconst page = window.location.search.get('page');
Attempts:
2 left
💡 Hint

Remember that useSearchParams returns a URLSearchParams object.

🔧 Debug
advanced
2:30remaining
Why does the URL not update when calling router.replace with new searchParams?

Given this code snippet inside a Next.js client component, why does the URL not update as expected?

const searchParams = useSearchParams();
const router = useRouter();

function updateCategory(cat) {
  const params = searchParams;
  params.set('category', cat);
  router.replace(`?${params.toString()}`);
}
ABecause searchParams is immutable and calling set on it does not change the original object.
BBecause router.replace requires a full URL, not just searchParams string.
CBecause useRouter cannot be used inside client components.
DBecause the function updateCategory is missing an async keyword.
Attempts:
2 left
💡 Hint

Check if searchParams can be modified directly.

❓ state_output
advanced
2:00remaining
What is the value of 'filter' after URL changes externally?

In a Next.js client component, the state variable filter is initialized from useSearchParams().get('filter'). If the user manually changes the URL's filter parameter in the browser address bar, what happens to the filter state variable?

NextJS
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';

export default function Filter() {
  const searchParams = useSearchParams();
  const [filter, setFilter] = useState(searchParams.get('filter') || 'all');

  return <div>Current filter: {filter}</div>;
}
AThe filter state remains unchanged until the component re-mounts or reloads.
BThe filter state updates immediately when the URL changes externally.
CThe filter state resets to 'all' automatically on URL change.
DThe component throws an error because state and URL are out of sync.
Attempts:
2 left
💡 Hint

Think about how React state works with initial values.

🧠 Conceptual
expert
3:00remaining
Why use URL searchParams for state in Next.js App Router?

What is the main advantage of syncing UI state with URL searchParams in a Next.js App Router application?

AIt prevents any client-side state updates, forcing all changes to reload the page.
BIt automatically improves server-side rendering performance by caching searchParams.
CIt allows users to share and bookmark the current UI state via the URL, enabling better navigation and persistence.
DIt disables browser back and forward buttons to avoid inconsistent UI states.
Attempts:
2 left
💡 Hint

Consider how URLs help users share or return to specific views.

Practice

(1/5)
1. What does the useSearchParams hook in Next.js App Router do?
easy
A. It fetches data from an API based on URL parameters.
B. It changes the URL path without reloading the page.
C. It reads and lets you access query parameters from the URL.
D. It manages local component state unrelated to the URL.

Solution

  1. Step 1: Understand the purpose of useSearchParams

    The hook is designed to read query parameters from the URL, making it easy to access values like ?page=2 or ?filter=active.
  2. Step 2: Compare with other options

    Changing URL path or fetching data are different tasks; useSearchParams specifically reads URL search parameters.
  3. Final Answer:

    It reads and lets you access query parameters from the URL. -> Option C
  4. Quick Check:

    useSearchParams reads URL query parameters = C [OK]
Hint: Remember: useSearchParams reads URL queries, not changes path [OK]
Common Mistakes:
  • Confusing useSearchParams with navigation or data fetching hooks
  • Thinking it changes the URL instead of reading it
  • Assuming it manages local state unrelated to URL
2. Which of the following is the correct way to import and use useSearchParams in a Next.js component?
easy
A. import { useSearchParams } from 'next/navigation'; const params = useParams();
B. import useSearchParams from 'next/router'; const params = useSearchParams();
C. import { useSearchParams } from 'next/router'; const params = useSearchParams();
D. import { useSearchParams } from 'next/navigation'; const params = useSearchParams();

Solution

  1. Step 1: Identify correct import source

    In Next.js App Router, useSearchParams is imported from 'next/navigation', not 'next/router'.
  2. Step 2: Check usage syntax

    The hook is called as useSearchParams(), returning the params object. Using useParams() is incorrect here.
  3. Final Answer:

    import { useSearchParams } from 'next/navigation'; const params = useSearchParams(); -> Option D
  4. Quick Check:

    Correct import and call = D [OK]
Hint: Import from 'next/navigation' and call useSearchParams() [OK]
Common Mistakes:
  • Importing from 'next/router' instead of 'next/navigation'
  • Calling useParams() instead of useSearchParams()
  • Using default import instead of named import
3. Given this Next.js component code snippet, what will be logged if the URL is ?page=3&sort=asc?
import { useSearchParams } from 'next/navigation';
export default function Page() {
  const searchParams = useSearchParams();
  console.log(searchParams.get('page'));
  console.log(searchParams.get('sort'));
  return null;
}
medium
A. 3 and asc
B. page and sort
C. null and null
D. undefined and undefined

Solution

  1. Step 1: Understand useSearchParams behavior

    useSearchParams returns an object with a .get() method to read query parameters by name.
  2. Step 2: Check the URL query parameters

    The URL has ?page=3 and ?sort=asc, so searchParams.get('page') returns '3' and searchParams.get('sort') returns 'asc'.
  3. Final Answer:

    3 and asc -> Option A
  4. Quick Check:

    searchParams.get('page') = '3', get('sort') = 'asc' [OK]
Hint: Use .get('key') to read exact query values [OK]
Common Mistakes:
  • Expecting keys instead of values
  • Confusing null with undefined for missing params
  • Not calling .get() method on searchParams
4. What is wrong with this Next.js component code that tries to read a search parameter?
import { useSearchParams } from 'next/navigation';
export default function Page() {
  const params = useSearchParams;
  const filter = params.get('filter');
  return <div>Filter: {filter}</div>;
}
medium
A. The import statement is incorrect; it should be from 'next/router'.
B. useSearchParams is not called as a function, so params is the function itself.
C. The component returns invalid JSX syntax with <div> tags.
D. The get method does not exist on the params object.

Solution

  1. Step 1: Check how useSearchParams is used

    The code assigns params = useSearchParams without parentheses, so params is the function itself, not the returned object.
  2. Step 2: Understand consequence of missing parentheses

    Calling params.get('filter') fails because params is a function, not the searchParams object with .get() method.
  3. Final Answer:

    useSearchParams is not called as a function, so params is the function itself. -> Option B
  4. Quick Check:

    Missing () after useSearchParams causes error = A [OK]
Hint: Always call useSearchParams() with parentheses [OK]
Common Mistakes:
  • Forgetting parentheses when calling hooks
  • Importing from wrong module
  • Misunderstanding JSX syntax for div
5. You want to build a Next.js page that shows a list filtered by a search term from the URL query parameter search. Which approach correctly updates the displayed list when the URL changes without a full page reload?
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';

export default function SearchPage() {
  const searchParams = useSearchParams();
  const [searchTerm, setSearchTerm] = useState('');

  // Which code below correctly updates searchTerm when URL changes?

  // A:
  // useEffect(() => {
  //   setSearchTerm(searchParams.get('search') || '');
  // }, [searchParams]);

  // B:
  // setSearchTerm(searchParams.get('search') || '');

  // C:
  // useEffect(() => {
  //   setSearchTerm(searchParams.search || '');
  // }, [searchParams]);

  // D:
  // useEffect(() => {
  //   setSearchTerm(searchParams.get('searchTerm') || '');
  // }, [searchParams]);

  return <div>Search: {searchTerm}</div>;
}
hard
A. Use useEffect with dependency on searchParams and call searchParams.get('search').
B. Call setSearchTerm directly without useEffect.
C. Use useEffect but access searchParams.search property (which does not exist).
D. Use useEffect but get 'searchTerm' key instead of 'search'.

Solution

  1. Step 1: Understand reactivity to URL changes

    useSearchParams returns a new object when URL changes, so useEffect with [searchParams] dependency runs on URL updates.
  2. Step 2: Correctly read the query parameter

    The parameter key is 'search', so use searchParams.get('search'). Accessing searchParams.search or wrong keys will fail.
  3. Final Answer:

    Use useEffect with dependency on searchParams and call searchParams.get('search'). -> Option A
  4. Quick Check:

    useEffect + searchParams.get('search') updates state on URL change = B [OK]
Hint: Use useEffect with searchParams dependency and .get('search') [OK]
Common Mistakes:
  • Calling setState outside useEffect causing infinite loops
  • Accessing non-existent properties on searchParams
  • Using wrong query parameter keys
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard