React Timeout
A component wrapper providing safe-to-use-with-react versions of
Set | Clear |
---|
setTimeout | clearTimeout |
setInterval | clearInterval |
setImmediate | clearImmediate |
requestAnimationFrame | cancelAnimationFrame |
When the component is unmounted the wrapper calls the Clear functions for you.
Installation
npm install --save react-timeout
React
import ReactTimeout from 'react-timeout'
React Native
The library also works with React Native ^0.16
and probably earlier versions:
import ReactTimeout from 'react-timeout/native'
Usage
Apply ReactTimeout using composition
class Example extends Component { .. }
const WithReactTimeout = ReactTimeout(Example)
or an annotation (not recommended)
@ReactTimeout
class WithReactTimeout extends Component { .. }
Invoke a safe setTimeout
from within the component.
const { setTimeout } = this.props.reactTimeout
const id = setTimeout(() => {
console.log(`The callback with ${id} fired!`)
}, 5000)
The callback function will be cleared if the component unmounts before the 5000ms
elapse.
Example
A full example is available in example/src/example.js
.
To run the example, clone the repository and run npm install && npm start
in the example/
folder.
Inspiration
The timer mixin recommended by the react-native README.md
.
Dan Abramov's article promoting stuff like this package