What is the difference between useMemo and useCallback?
Model answer
useMemo caches the result of a calculation between renders: useMemo(() => expensive(a), [a]). useCallback caches a function itself: useCallback(() => doIt(a), [a]), which is the same as useMemo(() => () => doIt(a), [a]).
Use them for expensive calculations or to keep stable references passed to memoised children or used in effect dependencies. They are not free, so do not wrap everything.
Learn this topic
React Performance: memo, useMemo, useCallback and When Not to Use Them in the course React.js Full Course: Beginner to Advanced.
Sign in to add your own answer.
More questions
- Why does a component re-render, and is re-rendering always bad?
- What does React.memo do?
- What is the React Compiler, and does it replace useMemo and useCallback?
- How do you lazy-load components in React?
- How do you render a very long list efficiently?
- Why can inline objects and functions as props hurt memoisation?