6
1

More than 1 year has passed since last update.

React18で追加されたAutomatic Batchingとは

Posted at

先月ついにReact18の正式版がリリースされました。
今回のリリースで追加された機能をコード付きでざっくり解説していきたいと思います。

紹介する機能は公式のReact Blogの下記記事に掲載されているものとなります。

Automatic Batching

useStateを使った下記のようなコードがあるとします。

function Sample1() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

  const increment = () => {
    setCount(count + 1);
    setFlag(!flag);
  };

  console.log("rendering");

  return (
    <div className="App">
      <button onClick={increment}>increment</button>
      {`count: ${count}, flag: ${flag}`}
    </div>
  );
}

increment関数を呼び出すとsetCount,setFlagでそれぞれcount,flagの状態を更新します。
2つのstateが更新されますが、再レンダリングは1回のみとなります。
sample1_1.gif

React18以前でもReactのイベントハンドラ内の複数の状態の更新は、バッチ処理として一回の再レンダリングにまとめてくれています。
ただし、下記のようなsetTimeoutPromiseのようなイベント内での更新はバッチ処理に対応していませんでした。

function Sample2() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

  const incrementTimeout = () => {
    setTimeout(() => {
      setCount(count + 1);
      setFlag(!flag);
    }, 100);
  };

  console.log("rendering");

  return (
    <div className="App">
      <button onClick={incrementTimeout}>increment</button>
      {`count: ${count}, flag: ${flag}`}
    </div>
  );
}

試しにReact17の環境でincremant関数を呼び出すと2回レンダリングされていることがわかります。
React18ではこのような場合でもバッチ処理を行ってくれるようになりました。

React17 React18
sample2_1.gif sample2_2.gif
6
1
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
6
1