Skip to content

feat: Debounce #900

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 55 commits into
base: next
Choose a base branch
from
Open

feat: Debounce #900

wants to merge 55 commits into from

Conversation

franky47
Copy link
Member

@franky47 franky47 commented Feb 7, 2025

Try it

pnpm add https://pkg.pr.new/nuqs@900

Documentation

This PR introduces a new method of rate-limiting URL updates, via debouncing rather than throttling (which was already possible via the throttleMs option).

Debouncing vs throttling

https://kettanaito.com/blog/debounce-vs-throttle

Throttling gives you predictable, consistent updates at a given rate. It's necessary to mitigate rate limits of the browser History API methods. One advantage of throttling is that, assuming there was sufficient inactivity before an event occurred, it will be emitted instantly, allowing for a reactive first update (and delaying subsequent ones).

Debouncing on the other hand gives you one eventual update after a given amount of inactivity has passed. Debouncing is useful for high-frequency inputs where only the final value is valuable, like moving a slider or typing some text.

Both of these mechanisms are in place to rate-limit updates to the URL. The internal state returned by useQueryState(s) is always updated instantly (just like React.useState would).

Specifying options

The throttleMs option is now marked as deprecated (but still supported until a later major, maybe v4, TBC), and replaced with a limitUrlUpdates option:

const [search, setSearch] = useQueryState('q', {
  limitUrlUpdates: {
    method: 'debounce', // debounce | throttle
    timeMs: 500
  }
})

// Can be defined with the builder pattern:
parseAsString.withOptions({ limitUrlUpdates: {...} })

// Can also be passed as a call option:
setSearch('foo', { limitUrlUpdates: {...} })

Shorthands

You can use the throttle and debounce shorthand methods, as well as the defaultRateLimit export to shorten your options:

import { debounce, throttle, defaultRateLimit } from 'nuqs' // or 'nuqs/server' in Next.js app router server code

parseAsString.withOptions({ limitUrlUpdates: debounce(500) })
parseAsString.withOptions({ limitUrlUpdates: throttle(500) })
setSearch(e.target.value, { limitUrlUpdates: defaultRateLimit }) // Reset to default

Interaction with other options

The startTransition function is used only when the URL is being updated, so for a debounced update, the loading state will only be triggered once the debounce time has elapsed, not while it is pending.

You'll likely want to set shallow: false to notify the server of updates, as I don't see many reasons to debounce a client-only URL update.

If you set both throttleMs and limitUrlUpdates, limitUrlUpdates will take precedence.

Tips & tricks

You will likely want to turn on debounce on high-frequency state updates. But often, inputs have multiple source of updates with different event firing rates, for example:

  • A slider (<input type="range">) has a very high event emitting frequency for onChange on drag that you may want to debounce, but clicking on a point on the slider track (not dragging) should likely be an instant update.
  • A text input has a high event emitting frequency for onChange when typing that warrant debouncing, but actions like clearing the input (select all + backspace) or pressing Enter should commit the value instantly.

One recommendation is to define debouncing when calling the state updater function:

function Search() {
  const [search, setSearch] = useQueryState("q")
  return (
    <input
      value={search}
      onChange={(e) =>
        setSearch(e.target.value, {
          limitUrlUpdates: e.target.value === '' ? undefined : debounce(500),
        })
      }
      onKeyDown={(e) => {
        if (e.key === "Enter") {
          // Send the search immediately when pressing Enter
          setSearch(e.currentTarget.value)
        }
      }}
    />
  )
}

Internal

Prep work:

  • Move shared code into src/lib, leaving only features at the top level
  • Move the throttle queue into a class to help with testing &
    multi-storage support later
  • Add stubs for debounce queue
  • Implemented new option
  • Added debounce queues (one per key) in front of the global throttle queue

Tasks

  • Tests
  • Documentation
  • Memory usage: cleanup debounce queues after usage, cleanup timeout abort event listeners
  • Handle infinity timeouts
  • Add abort method to cancel a pending debounced update
  • Make auto-abort on navigation work in the Next.js app router
  • Elect repro-702 to shared e2e test (to validate queued queries)
  • Restore the default behaviour of adapters (auto-resetting the throttled queue) to avoid breaking custom ones.
  • Investigate double-update mitigation (debounced update followed by a pre-empted default set, eg: pressing Enter to submit immediately on a debounced input).

See discussions #373 & #449.

Closes #291.

Copy link

vercel bot commented Feb 7, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
nuqs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 25, 2025 7:23pm

@franky47 franky47 added this to the 🪵 Backlog milestone Feb 7, 2025
Copy link

pkg-pr-new bot commented Feb 7, 2025

pnpm add https://pkg.pr.new/nuqs@900

commit: 0e4aa46

@Kavan72
Copy link

Kavan72 commented Feb 10, 2025

Can't wait to test this feature 😁

@franky47
Copy link
Member Author

franky47 commented Feb 10, 2025

@Kavan72 you can! Follow the preview install instructions here, and the docs from the PR description:

npm i https://pkg.pr.new/nuqs@900

franky47 added 10 commits April 23, 2025 14:06
This can't work since we do a hard load of the page, losing queued values.
And partially revert "fixes" made to the tests to bring back isolation.
- Detect userland navigation in next/app, this is kind of tedious but
since Next.js also patches the History API and calls it on its own in
our nuqs updates flow, we need an alternate approach (spin lock
mutex-like).

We should now have the whole debounce experience everywhere,
checking with CI on various Next.js versions.
- Rename repro-702 into life-and-death, testing component
mount/unmount with pending states
- Move shared tests into a single fixture for faster bootstrapping
- Assert against null transitive states (requires waiting for router.isReady
in the pages router, see issue #290)
- Order the routes definitions in React SPA, RRv6 & RRv7
to avoid merge conflicts in the future.
Some adapters will need to reset the throttle queue in different
ways, to ensure a stable number of renders and initialising mounted
components with queued states in the right way.

By default, the queue is reset as it was before, and adapters can opt-out
of this auto-reset and have the responsibility of doing it when a URL
udpate occurs.
This caused issues in tests where we need to reset the queue
in the same tick as after pushing changes. It's unlikely to
have an effect in userland apps, but it makes the behaviour more
robust and consistent.
@devhasson
Copy link

I can't wait for this PR to be merged 👀

@franky47
Copy link
Member Author

franky47 commented Apr 25, 2025

@devhasson have you tried it? See the "try it" section in the PR description.

It's in a state where there are a lot of internal changes that should not (theoretically) affect userland behaviours, but I'm looking for folks to try it and give feedback of things that might have been missed by the test suite.

Earlier this week I've been working at getting the "auto-abort pending updates on user navigation" detection working, it's now green in all adapters, but I'd like to try it in a couple of actual apps before it lands, just in case we end up with another aha moment like last week.

One last suite of tests I'd like to add relates to the introduction of useSyncExternalStore inside the hooks, to deal with reactive optimistic state. For this I'll need to test it in a Suspense-heavy application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Debounce URL updates
5 participants