useVersionedAction

This Hook is available since v1.7.0.

A low-level React Hook designed to facilitate the use of "versioned" actions, commonly employed in asynchronous scenarios for filtering operations to ensure only the latest action is executed.

Scenes

  • Asynchronous operation filtering: Handling multiple asynchronous operations, executing only the latest operation, ignoring "expired" ones.

Demo

Source
Value:
Click to Fetch

Usage

When doSomething() is called consecutively, only the most recent operation is executed, avoiding "expired" operations that could lead to screen flicker or unexpected results.

const [incVersion, runVersionedAction] = useVersionedAction() const doSomething = async () => { // Increment the version number with incVersion() const version = incVersion() // Asynchronous operation, like fetching data const result = await fetchSomething() // Ensure only the latest action is executed with runVersionedAction() runVersionedAction(version, async () => { setResult(result) }) }

Source

Click links below to view source on GitHub.

API

const [incVersion, runVersionedAction] = useVersionedAction()

Returns

export type UseVersionedActionReturns = readonly [ /** * Increment the version number and return the current version number */ incVersion: () => number, /** * Executes the versioned operation, only if the version number matches, ensuring that only the latest action is executed */ runVersionedAction: <T extends AnyFunc>(version: number, handler: T) => ReturnType<T> | undefined, ]