useMemo hook

DEMO
T
Timon
A good spot to rustle up some grub!
P
Pumbaa
Slimy and satisfying!
without useMemo
Average:3.7
with useMemo
Average:3.7
useMemo is a hook that optimises performance. It allows us to only run a costly calculation when its dependencies change rather than every render.

In the above example, we don't need to recalculate the average rating each time we enter a character into the input box. Thus, we memoise the rating.
WithoutMemo.jsx

WithUseMemo.jsx
const WithoutUseMemo = () => {
  const name = useInput();
  const [reviews, setReviews] = useState(reviewData);

  // expensive calculation
  const average = reviews.reduce((acc, review) => acc + review.rating, 0) / reviews.length,
  console.log(average);

  return (
    <>
      <Average average={average} />
      <Input {...name} placeholder="Enter your name" />
    </>
  );
};

export default WithoutUseMemo;

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React