Avoid Unnecessary Re-Renders In React With Usememo And Usecallback

TopicSource
ReactReact 16: The Complete Course (incl. React Router 4 & Redux) - Udemy

Both useMemo and useCallback are tools for optimizing performance by minimizing unnecessary re-renders in your React components. They achive this by memoizing values and functions.

useMemo

useMemo is used to memoize and cache the result of a computation so that it is only recalculated when its dependencies change.
It takes two arguments: a function and an array of dependencies.
The function is executed, and its result is cached until one or more dependencies in the array change.
Useful when you want to avoid unnecessary recalculations, especially in complex and expensive computations.

One important note: You should not simply use useMemo on every component, to avoid re-renders, since useMemo itself also has a cost of memoizing and comparing the values. Only do this on some key parts of your app to avoid the update of child components.

Example:

Copy code  
const memoizedValue = useMemo(() => computeExpensiveValue(dep1, dep2), [dep1, dep2]);  

useCallback

useCallback is used to memoize and cache a callback function so that it remains the same between renders, as long as its dependencies haven't changed.
It takes two arguments: a callback function and an array of dependencies.
Useful when passing callbacks to child components, preventing them from re-rendering unnecessarily.
Example:

const memoizedCallback = useCallback(() => handleButtonClick(dep1), [dep1]);  

  1. React Hydration