Flaque / use-timeout

A react-hook for accessing setTimeout without constantly resetting.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

use-timeout

License

A react-hook for accessing setTimeout without constantly resetting.

Install

yarn add @flaque/use-timeout

Usage

const [setTimeoutHook, clearTimeoutHook] = useTimeout();

setTimeoutHook(() => {
  console.log("It's been 10000 miliseconds!");
}, 10000);

// ...

clearTimeoutHook(); // Stops the timeout before it happens

Why?

If you call setTimeout inside of a function component like this:

// BAD DONT DO THIS
function MyComponent() {
  const [isLoading, setIsLoading] = useState(false)
  
  setTimeout(() => {
    setIsLoading(true)
  }, 1000)
  
  return <p>{isLoading ? "loading" : "finished"}</p> 
}
// BAD DONT DO THIS 

Then it'll get reset when the function renders. That can lead to weird unexpected behavior. use-timeout uses hooks to keep an internal reference to the timeout to avoid any weirdness.

About

A react-hook for accessing setTimeout without constantly resetting.


Languages

Language:TypeScript 100.0%