1
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?

Reactの useMemo をかんたんに理解する:「結果を覚える」だけの仕組み

Posted at

はじめに

Reactでfilter()やmap()などの処理を毎回実行していると、
再レンダーのたびにアプリが重くなることがあります。
その無駄な再計算を防ぐのが useMemo です。

useMemoの基本

const value = useMemo(() => {
  return heavyCalculation();
}, [dependency]);

以上のコードの意味

「dependency が変わったときだけもう一度計算して、
それ以外は前回の結果を使う」

例:filter処理を最適化

const filteredSpots = useMemo(() => {
  return spots.filter((spot) => {
    if (filters.wifi && !spot.wifi) return false;
    if (filters.power && !spot.power) return false;
    return true;
  });
}, [spots, filters]);

以上のコードの意味

  • spots と filters が変わった時だけ再実行

  • ピンをクリックなど他のstate変更では再計算しない

  • 無駄なfilter()を防いで高速化

まとめ

  • useMemo は「計算結果を覚えておく」Hook

  • [] の中に書いた値が変わった時だけ再計算

  • 重い処理(filter, sort, reduce)を最適化したい時に使う

1
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
1
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?