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 23 commits into
base: next
Choose a base branch
from
Open

feat: Debounce #900

wants to merge 23 commits into from

Conversation

franky47
Copy link
Member

@franky47 franky47 commented Feb 7, 2025

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
  • Handle infinity timeouts
  • Investigate double-update mitigation (debounced update followed by a pre-empted default set, eg: pressing Enter to submit immediately on a debounced input).
  • Add abort method to cancel a pending debounced update
  • Test what happens if the pathname changes while the update is pending (it will apply on the new pathname, but should it?)

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 Mar 27, 2025 1:49pm

@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: 25a36b2

@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

@Kavan72
Copy link

Kavan72 commented Mar 1, 2025

Have you had a chance to test it? Do you have any feedback?

One issue I'm encountering is that it's possible (well it was with throttle too but harder to trigger) to schedule a search params update, perform a navigation (eg: clicking a Link), and the search params apply on the destination page (potentially overriding some that were applied by the link).

The tests that confirm this behaviour pass on my machine but fail in CI, so I'll have to look into that.

The other point is about cascading updates to the same key with different options. If scheduling a debounced update, then a throttled update, the throttled one will fire first, and the debounced one will overwrite it later. This feels like it breaks the intent of "last update wins". One case where this is visible is in search fields: you want to debounce in onChange, but want to flush/emit the update immediately in some cases (clearing the search field, or pressing Enter). Those immediate updates should abort the debounced update.

Sorry, I didn’t get a chance to test this, but here are some of my thoughts related to the current issues:

  1. If changes are pending and the user navigates away, we have two options: one is to push the changes into history before navigating, so the back button doesn’t break; the other is to simply abort the pending changes and navigate.
  2. If an update is pending and the user presses Enter to forcefully update the same key, then, in my opinion, only the last update (the forced one) should be considered.

@franky47
Copy link
Member Author

franky47 commented Mar 1, 2025

Thanks for your feedback. I agree with point 2, I updated the implementation to do just that yesterday.

For point 1, I didn't think of the "apply before navigating", which makes sense, unfortunately I doubt we'll be able to reliably inject custom behaviours before navigation occurs in all frameworks (and even doing so after navigation would have its issues).

I was thinking of providing a way to abort pending debounced updates, what do you think?
https://bsky.app/profile/francoisbest.com/post/3lircw7dsuk2d

@franky47 franky47 mentioned this pull request Mar 6, 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