Q1. How does useMemo improve performance?
This is useful for derived data or complex calculations.
useMemo memoizes the result of a computation, preventing expensive recalculations on every render if dependencies haven't changed.This is useful for derived data or complex calculations.
Q2. Give an example where useMemo is beneficial.
Suppose you have a large list and you need to filter it based on a search term.
Without
With
Without
useMemo, the filtering runs on every render.With
useMemo, it only runs when the list or search term changes.Q3. What are the downsides of useMemo?
Use it only when the computation is expensive and the dependencies change infrequently.
useMemo adds memory overhead and can make code less readable if overused.Use it only when the computation is expensive and the dependencies change infrequently.
Q4. Can useMemo be used for objects to prevent child re-renders?
Yes, if you pass an object as a prop to a memoized child, you can use
useMemo to stabilize the object reference so that the child doesn't re-render unnecessarily.Q5. How is useMemo related to React.memo?
Both aim to optimize performance by avoiding unnecessary work.
They are often used together:
useMemo memoizes values, React.memo memoizes components.They are often used together:
useMemo to create stable props for React.memo components.