Skip to content

Drop-in replacement for `useState` with throttling capabilities.

Notifications You must be signed in to change notification settings

PatrickDesign/useThrottledState

Repository files navigation

use-throttled-state

Drop-in replacement for `useState` with throttling capabilities. Access local state immediately while dispatching data to worker functions at a throttled rate.

NPM JavaScript Style Guide

Install

npm install --save use-throttled-state

Usage

useThrottledState allows you to easily work with data locally while dispatching any updates to a worker function in the background. The worker function is only called once per throttleRate time interval.

Here is a quick writeup with examples!

Interface:

import useThrottledState from "use-throttled-state"

const [value, setValue] = useThrottledState(
  initialValue,
  throttleRate, // In milliseconds
  workerFunction
)

Example with 500 ms throttleRate: useThrottledState example with 500 ms throttleRate

vs. 2500 ms throttleRate: useThrottledState example with 2500 ms throttleRate

import React from "react"
import useThrottledState from "use-throttled-state"

const doWork = (query) => {
  //... do expensive work with the query ...
  db.query(query)
}

const Example = () => {
  const [searchQuery, setSearchQuery] = useThrottledState("", 550, doWork)

  return (
    <>
      <input
        id="query"
        onChange={(event) => {
          setSearchQuery(event.target.value)
        }}
        value={searchQuery}
      />
      <div>Local data: {searchQuery}</div>
    </>
  )
}

A common scenario is wanting to limit the number of context updates that occur as a user types. This setup might look like:

import useThrottledState from "use-throttled-state"

...

const { setValueFromContext, valueFromContext } = useContext(SomeContext)

const [localValue, setLocalValue] = useThrottledState(
  valueFromContext,
  500,
  (newValue) => {
    setValueFromContext(newValue)
  }
)

License

MIT © @patrickDesign


This hook is created using create-react-hook.

About

Drop-in replacement for `useState` with throttling capabilities.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published