1.0.0 • Published 4 years ago

use-throttled-state v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

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.

1.0.0

4 years ago

0.0.21

4 years ago

0.0.22

4 years ago

0.0.2

4 years ago

0.0.15

4 years ago

0.0.1

4 years ago