先月ついに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回のみとなります。
React18以前でもReactのイベントハンドラ内の複数の状態の更新は、バッチ処理として一回の再レンダリングにまとめてくれています。
ただし、下記のようなsetTimeout
やPromise
のようなイベント内での更新はバッチ処理に対応していませんでした。
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 |
---|---|