useCallback and useMemo hooks in React are used for performance improvements.
useMemo returns a memoized value. For example an event handler in a component is re-created every re-render. Maybe event handler is doing a heavy operation so even if we make a small change in our JSX, the whole component re-renders and thus, event handler is re-created and it starts doing that heavy operation again. This causes a big performance problem.
useMemo will perform a shallow comparison of props and will re-render only when the props change. With useMemo hook, we’ll be able to cache expensive functions so that they will only run when a specific pieces of data change. It will take dependencies and only re-render when the dependencies change.
This is similar to useMemo , it takes a function as the first argument and an array of dependencies as the second argument. The difference is that useCallback returns the function and not the result of the function. Like the useMemo, it will not recreate the function unless a dependency changes.
And that’s it for this article, I hope you enjoyed and learned a lot.