7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactのclassでlodashのdebounceやthrottleを使う

Last updated at Posted at 2019-10-07

Reactで lodash を使って、連続処理を制御したいときに、意外とトリッキーだと感じたのでメモしておく。

class LodashSample extends React.Component {
  constructor(props) {
    super(props);
  }
  onInputChange = _.debounce((value) => {
    // Implement Logic here
    console.log('debounce!!');
  }, 300)
  throttleMethod = _.throttle((value) => {
    // Implement here
    console.log('throttle!!');
  }, 300)
}

こんな感じに書くと綺麗に書ける。

最初は下記のような感じで書いてしまった。

  onInputChange(value) {
    _.debounce((value) => {
      console.log('debounce!!');
    }, 300);
  }

こうすると、 debounce の中のfunctionが呼び出されない。
というのも、 debounce は、メソッドを返すので、メソッドをCallする部分がないからそりゃ呼ばれないという話。

ちょっと癖があってミスったりするけど意味が理解できるとしっくりくる。

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?