one-hook
Size
0.29 kb
View source

useThrottleFn

A throttle function, reactified.

Ensures that a function is only executed once in a specified time interval, no matter how many times it is invoked.

Installation

npm install @1hook/use-throttle-fn

Usage

import {  } from '@1hook/use-throttle-fn'

The useThrottleFn hook accepts an interval in milliseconds and returns a throttle function.

The first call executes right away, while subsequent calls within interval are throttled.
The final call is scheduled to run after the interval expires.

const {  } = (1000)

(() => .('Executes immediately'))
(() => .('Skipped'))
(() => .('Scheduled to execute after 1000ms'))

Override the default interval:

const { throttle } = useThrottleFn(1000)

throttle(() => console.log('Executes immediately'))
throttle(() => console.log('Scheduled to execute after 500ms'), 500)

Use trailing: false to avoid scheduling the last call:

const {  } = (1000, { : false })

(() => .('Executes immediately'))
(() => .('Skipped'))

Cancel pending executions:

const { throttle, cancel, isPending } = useThrottleFn(1000)

isPending && cancel()

When the component unmounts, pending executions are automatically canceled.

API Reference

UseThrottleFnOptions

The options of the useThrottleFn hook.

PropTypeDefault
trailing?
boolean
true

UseThrottleFnReturn

The return value of the useThrottleFn hook.

PropTypeDefault
isPending
boolean
-
cancel
() => void
-
throttle
(callback: () => any, interval?: number | undefined) => void
-

On this page