Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Last active October 16, 2017 01:11
Show Gist options
  • Save kevinwucodes/a822caa262608326e1adb37b815f361d to your computer and use it in GitHub Desktop.
Save kevinwucodes/a822caa262608326e1adb37b815f361d to your computer and use it in GitHub Desktop.
ways to use debounce in React

Ways to use debounce in React

In Constructor

inspired by: http://blog.revathskumar.com/2016/02/reactjs-using-debounce-in-react-components.html

class Test extends React.Component {
  constructor(props) {
    super(props)

    this.callworker = this.callworker.bind(this)
    this.doDifficultWork = debounce(this.doDifficultWork, 500)
  }

  callworker(e) {
    this.doDifficultWork(e)
  }

  doDifficultWork(e) {
    console.log('doing difficult work')
  }

  render() {
    return (
      <div>
        <button onClick={this.callworker}>click</button>
      </div>
    )
  }
}

In Method

inspired by: https://medium.com/gitconnected/debounce-react-and-redux-code-for-improved-performance-4b8d3c19e305

class Test extends React.Component {
  constructor(props) {
    super(props)
  }

  doDifficultWork = debounce((e) => {
    console.log('doing difficult work')
  }, 500)

  render() {
    return (
      <div>
        <button onClick={this.doDifficultWork}>click</button>
      </div>
    )
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment