useCallback and useMemo hooks in React are used for performance improvements.

useMemo:

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.

useCallback:

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.

πŸ‘‹ Hey, I'm Osman Armut
Hi, I'm Osman Armut. I'm a self taught frontend developer that has a great passion for Javascript and React ecosystem. I use articles in my personal learning journey and I like to share my knowledge to help people.

πŸ’¬ Leave a comment

Your email address will not be published.

We will never share your email with anyone else.