When would you use useMemo in React?
Answer
In React, useMemo is a hook that is used to optimize the performance of a component by memoizing the result of a function. It is used to prevent unnecessary re-renders of a component by caching the result of a function and returning it when the inputs to the function have not changed. This can be useful when a component is rendering frequently and the result of a function is expensive to compute. By using useMemo, we can avoid recomputing the result of the function on every render and only compute it when the inputs have changed.
One example of when to use useMemo is when rendering a list of items. If the list is large and each item requires a complex computation to render, it can be expensive to re-render the entire list on every update. By using useMemo, we can cache the result of the computation for each item and only recompute it when the input data for that item has changed. This can greatly improve the performance of the component and reduce unnecessary re-renders.
const MyComponent = ({ data }) => {
const expensiveComputation = (item) => {
// perform complex computation on item
return result;
};
const memoizedData = useMemo(() => {
return data.map(item => expensiveComputation(item));
}, [data]);
return (
<ul>
{memoizedData.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
In the example above, we have a component that renders a list of items. The expensiveComputation function performs a complex computation on each item in the data array. By using useMemo, we can cache the result of the computation for each item and only recompute it when the data array has changed. This can greatly improve the performance of the component and reduce unnecessary re-renders.
Related React job interview questions
Which methods would you use to handle events in React?
React JuniorHow would you avoid binding in React?
React JuniorWhat method would you use to check and improve speed of React app?
React JuniorWhich methods would you use to conditionally add attribute to components in React?
React JuniorHow would you use validation on props?
React Junior