react-debounce-props
Tiny render-prop/HOC/hook component for props/state debouncing
Install
Using npm
npm i react-debounce-props --save
Then, use it as usual:
// using ES6 modulesimport { Debounce } from 'react-debounce-props' // using CommonJS modulesconst { Debounce } = require('react-debounce-props')
1998 Script Tag (UMD build)
The UMD build is also available on unpkg:
<script src="https://unpkg.com/react@16.4.1/umd/react.production.min.js"></script><script src="https://unpkg.com/react-debounce-props"></script>
The package is avalable on window.ReactDebounceProps
Usage
Hook
import React, { useState } from "react";import ReactDOM from "react-dom";import { useDebounce } from "react-debounce-props"; let App = () => { let [value, setValue] = useState(""); let debouncedValue = useDebounce(value, 250); return ( <div className="App"> <input value={value} onChange={e => setValue(e.target.value)} placeholder="Type smth..." /> <div> Normal value: <b>{value}</b> </div> <div> Debounced value: <b>{debouncedValue}</b> </div> </div> );}; const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);
render-prop
Debounce state
This lib can easily replace react-debounce-input cause it is more generic.
import React from 'react'import ReactDOM from 'react-dom'import Debounce from 'react-debounce-props' class App extends React.Component { state = {} render() { return ( <div> <input value={this.state.value} onChange={e => this.setState({ value: e.target.value })} placeholder="Type smth..." /> <div> Normal value: <b>{this.state.value}</b> </div> <Debounce debouncedValue={this.state.value} wait={250}> {({ debouncedValue }) => ( <div> Debounced value: <b>{debouncedValue}</b> </div> )} </Debounce> </div> ) }} const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement);
Debounce props
You can also debounce props passed from parent components:
import Debounce from 'react-debounce-props' let MyComponent = ({ frequentlyUpdatedProp }) => ( <Debounce lessFrequentlyUpdatedProp={frequentlyUpdatedProp} wait={250}> {({ lessFrequentlyUpdatedProp }) => ( <b>{lessFrequentlyUpdatedProp}!</b> )} </Debounce>)
as well as from other render-props (e.g. from new React context):
import Debounce from 'react-debounce-props' let MyComponent = () => ( <SomeContextConsumer> {frequentlyUpdatedProp => ( <Debounce lessFrequentlyUpdatedProp={frequentlyUpdatedProp} wait={250}> {({ lessFrequentlyUpdatedProp }) => ( <b>{lessFrequentlyUpdatedProp}!</b> )} </Debounce> )} </SomeContextConsumer>)
High order component
Cause render-props approach is more powerful this lib can replace HOC of react-debounced-props as well.
Use withDebouncedProps
for that:
import { withDebouncedProps } from 'react-debounce-props' const MyDebouncedComponent = withDebouncedProps( { frequentlyUpdatedProp: 42 }, 200)(MyComponent);