7
7

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のuseEffect内でsetIntervalを使いたい時はuseIntervalを使ったら楽

Posted at

useEffect内のsetIntervalでstateを更新する記事があまりなかったので、 書き残しておきます。

useEffectの中で、 setIntervalを使い、 定期的にstateを更新しようとすると、ちょっとした工夫が必要になります。詳細は以下の記事を読んでいただけたら分かると思います。
Making setInterval Declarative with React Hooks

上の記事が元ネタになるわけですが、 すぐに使えるようnpmに公開してくれている方がいました。
https://github.com/Hermanya/use-interval#readme

npm install use-interval
import React, { useState } from 'react';
import useInterval from 'use-interval';

const App: React.FC = () => {
  const [state, setState] = useState<number>(0);

  useInterval(() => {
    setState(state + 1);
  }, 1000);

  return (
    <div>{state}</div>
  );
}
7
7
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
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?