React Memoization
In simple terms, memoization is a process that allows us to cache the values of recursive/expensive function calls so that the next time the function is called with the same argument(s), the cached value is returned rather than having to re-compute the function.
This ensures our applications run faster because we avoid the time it would usually take to re-execute the function by returning a value that’s already stored in the memory.
Any of the following methods can be used:
useMemo
useMemo allows us to memoize functions that are very expensive or have a very high number of calculations during each re-rendering, and we don’t want to run such functions every time we render. useMemo takes a single function and an array of arguments. useMemo will only execute that function when those arguments change. If we pass it an empty array, then it will run once, and if we don’t pass it an empty array, then it will run on every re-render. In useMemo the result is memoized if we pass the same argument, then it returns the memoized result without actually running the whole process.
useCallback
This works as useMemo but the difference is that it’s used to memoize function declarations.
In REACT when a parent component re-render inside a parent, a child component also re-renders. At each re-render child component will re-execute its functions. Using call back function, the re-execute of function will solve the issue. useCallback is a built in Hook in React, it used to return a memoized version of callback function. Memoization does the remembering or caching the results of the function. Memoized version of callback only changes if one of the dependencies has changed. The cashed result is returned when same inputs are called again. Function and a list of dependencies are the input parameters to the useCallback.
useCallback is used to prevent unnecessary re-rendering in Parent component, when passing callbacks to the child components.
React.meno()
React.memo() is an HOC (higher-order component) which takes a component and returns an enhanced component. When React re-renders this enhanced component, it will shallow compare the new props object passed to this component with the old one. If shallow compare says that props are the same as last time then React skips re-rendering the enhanced component (and therefore all other component it re-renders).
You might be wondering why React doesn’t shallow compare props by default. That’s because there’s a high chance the comparison will be false and in such case, we’ll pay both the comparison cost and the re-render cost.