Skip to the page

State management and data fetching · mid

URL as state: filters, search and pagination

Shareable view state (filters, sort, page, search query) should live in the URL query string as the single source of truth, parsed and validated into typed state, and updated with replace while typing and push for committed changes.

The notes

What you must know

  • The URL is the source of truth; do not keep a second copy in useState synced with two effects (that causes loops).
  • Parse and validate: unknown sort values or negative pages fall back to defaults (zod or a small parser; nuqs is a popular helper in Next.js).
  • Use router.replace (or history.replaceState) for every keystroke and push when the user commits a filter, so Back works sensibly. Debounce URL writes for typing.
  • Keep ephemeral UI (open dropdowns, hover) out of the URL.
  • Remove default values from the URL and keep a stable parameter order so URLs (and caches) are canonical.
  • Scroll restoration on Back: cached list data plus the router's or browser's restoration; virtualised lists need an anchor index.
  • In Next.js, searchParams is request-time data: read it inside <Suspense>, and pass the values into "use cache" functions so they become cache keys.

The red pen

Common traps: mistake → fix

  • Mistake: "Sync URL and state with two effects"

    Fix: infinite loops and double renders.

  • Mistake: "Push a history entry per keystroke"

    Fix: Back becomes useless.

  • Mistake: "Trust URL params"

    Fix: they are user input; validate them.

Easy to hard

Questions interviewers ask, easy to hard

  1. Filters, sort and page live in React state, so Back loses them and links are not shareable. Redesign it.
  2. push vs replace for each keystroke?
  3. How do you restore scroll when coming back from the product page?
  4. In Next.js, how does reading searchParams affect caching and Suspense?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview