Q1. What is the useMemo hook?
It takes a function and a dependency array, and returns the memoized value.
The function runs only when a dependency changes, preventing expensive recalculations on every render.
useMemo is a React hook that memoizes the result of a computation.It takes a function and a dependency array, and returns the memoized value.
The function runs only when a dependency changes, preventing expensive recalculations on every render.
Q2. When should you use useMemo?
Use it for expensive calculations that you don't want to re-run on every render.
For example, filtering a large array, complex data transformations, or creating objects that cause child re-renders due to reference changes.
For example, filtering a large array, complex data transformations, or creating objects that cause child re-renders due to reference changes.
Q3. How is useMemo different from useCallback?
Both accept a dependency array.
useMemo memoizes a value, while useCallback memoizes a function.useMemo returns the result of the function, useCallback returns the function itself.Both accept a dependency array.
Q4. What happens if you omit the dependency array?
If omitted,
If the array is empty, the value is computed once and never updates.
useMemo will compute a new value on every render, which defeats its purpose.If the array is empty, the value is computed once and never updates.
Q5. Can useMemo cause performance issues?
If used unnecessarily,
Use it only when the computation is truly expensive.
Premature optimization can harm readability and performance.
useMemo adds overhead.Use it only when the computation is truly expensive.
Premature optimization can harm readability and performance.
