0
0

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)

Last updated at Posted at 2019-11-06

こんにちは。
React の勉強中で、データの更新とは異なるタイミングでそのデータを描画更新に渡す方法を習得しようとしています。10 ms 毎に更新される変数 cum の値を、1000 ms 毎に描画したい想定です。

手始めに、"Making setInterval Declarative with React Hooks" (useInterval) を見つけ、変数 cum (10 ms 毎に値を更新: +1)の値を、描画更新用の変数 num へ代入を行うことで(1000 ms 毎)、描画実行させてみました。描画上で更新される num の値を確認すると +100 づつ増加し想定通りの動きでした。

ただし、描画更新用の変数へ代入するという方法は冗長のような気もしますし、データとして巨大な要素数の配列などを扱いたくなった場合は処理が重くなるかなと考えています。

num: 99 → 199 → 299 → 399
App.jsx
import React, { useState } from 'react';
import useInterval from '../src';

function App(props) {
  const [num, setNum] = useState(0);
  const [cum, setCum] = useState(0);

  useInterval(() => {
   setCum(cum + 1);
  }, 10);

  useInterval(() => {
    setNum(cum);
  }, 1000);

  return (
    <div>
      <p>num: {num}</p>
    </div>
  );
}

export default App;
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?