Skip to content
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

feat: Debounce #900

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

feat: Debounce #900

wants to merge 14 commits into from

Conversation

franky47
Copy link
Member

@franky47 franky47 commented Feb 7, 2025

WIP, opening it early to have the nice round PR number 🤭

Documentation

This PR introduces a new method of rate-limiting URL updates, via debouncing rather than throttling (that 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
  • 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 Feb 12, 2025 3:37pm

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

pkg-pr-new bot commented Feb 7, 2025

Open in Stackblitz

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

commit: 92b44ce

@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

- 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
Also renamed the property to avoid clashes with the throttleMs option.
Removed premature optimisation: skipping scheduling a flush
returns a different Promise reference, breaking existing behaviour.
@franky47 franky47 marked this pull request as ready for review February 12, 2025 10:49
@franky47 franky47 added the feature New feature or request label Feb 12, 2025
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
2 participants