use-delayed-state
React hook for setting State with delay
This is an enhanced useState
hook which accepts delay for setState
as an extra argument. In most basic form it works same as React useState
hook.
Use cases
It can be used for debouncing which simply delays all consecuative attempts for setting a state and if the last call persist for enough time the actual setState
runs.
It is also a handy tool for applying timing logics inside react components e.g. Showing a notification for few seconds.
Install
npm install --save use-delayed-state
Usage
import React from 'react'
import useDelayedState from 'use-delayed-state'
export default function myComponent() {
const [state, setState] = useDelayedState(
'Hello, I will be change in 5 seconds'
)
setState('I am new State', 5000)
return <div>{state}</div>
}
In above example State
will be updated after 5 second.
Debouncing example is more advance implementation of this hook which the source code is available here.
Usage details
const [state, setState, cancelSetState] = useDelayedState(initialState);
setState(newState);
setState(newState, duration);
cancelSetState();
setState(newState);
setState(futureState, 2000);
License
MIT © makannew