0
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 3 years have passed since last update.

React内でsetIntervalを実現する (LiveScript版)

Posted at

ReactでsetIntervalが効かなくて困ったので調査
スマートな解決方法が載っている記事がヒットしたので備忘録として残しておく。

参考記事: Making setInterval Declarative with React Hooks

数時間以上React Hooksを使っていたら、
おそらく興味をそそられる問題にぶつかったことでしょう。
setIntervalを使っても思ったようにはいかないのです。

という訳でこの記事のコードをLiveScriptで書き直したのがこちら。
JavaScriptのコードは上記の記事を参考。

functions/use-interval.ls
require! {
  react: {use-ref, use-effect}
}

module.exports = (cb, delay) !->
  saved-cb = use-ref!
  use-effect do
    -> saved-cb.current = cb
    [cb]
  use-effect do
    ->
      if delay isnt null
        id = set-interval _, delay <| -> saved-cb.current!
        return -> clear-interval id
    [delay]
0
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
0
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?