IT未経験者でも分かりやすく学べる技術ブログ
useMemoの使い方
2025-01-09
useMemo は、重い計算処理を効率化するための React のフックです。
通常、コンポーネントが再レンダリングされるたびに計算処理が実行されますが、useMemo を使うと 必要なときだけ計算を実行 できます。
これにより、パフォーマンスが向上 し、画面の動作がスムーズになります。
似た概念にuseCallbackがありますが、こちらは関数自体を保持します。
useMemoは、以下のような構文で記述できます。
const cachedValue = useMemo(calculateValue, dependencies)
サンプルコードは下記です。 otherValueが変化したときだけ重い計算処理を再計算します。 useMemoで定義される計算は以下の計算になります。
a. Array.from({length:1000000}, (_, i) => i + otherValue)
i. 長さが 1,000,000(=100万)の配列を作成します。
ii. 上記の配列のindex番号を配列化して各要素にotherValueを足します。
ex) otherValue = 5の時、[0 + 5, 1 + 5, 2 + 5, ..., 999999 + 5]
b. .reduce((a, b) => a + b, 0)
i. 上記の配列内のすべての要素を加算して合計を求めます。
import { useMemo, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
const [otherValue, setOtherValue] = useState(0);
const result = useMemo(() => {
console.log("calculate values!", otherValue);
return Array.from({ length: 1000000 }, (_, i) => i + otherValue).reduce(
(a, b) => a + b,
0
);
}, [otherValue]);
return (
<div>
<p>Result: {result}</p>
<p>Count: {count}</p>
<p>OtherValue: {otherValue}</p>
<button onClick={() => setCount(count + 1)}>Countの変更</button>
<button onClick={() => setOtherValue(otherValue + 1)}>
OtherValueの変更
</button>
</div>
);
}
[解説]
実際の画面については、以下のプレビュー参照
もしプレビューが表示されていない場合は以下の手順で表示
コマンドパレットを開く(mac: Shift+command+P, win: Shift+Ctl+P) > 「Open Preview」と入力 > 「CodeSandBox: Open Preview」を選択
この記事を書いた人
Tさん
別業界から転職1年で
Webフルスタックとして活動中
これからエンジニアになりたい!
駆け出しエンジニアが最短で
成長できる方法を発信
関連記事
ReactHooksこれだけでOK!