Mid From PDF React React.js

How do useMemo and useCallback help with performance?

useMemo:

useMemo is a hook that memoizes the result of an expensive function call and only

recomputes the value when one of the dependencies changes.

  • Use case: Expensive calculations or operations that don’t need to be recalculated on

every render.

Example:

const expensiveValue = useMemo(() => computeExpensiveValue(a, b),

[a, b]);

// expensiveValue will only recompute when `a` or `b` changes

useCallback:

useCallback is used to memoize a function so it doesn’t get recreated on every render.

  • Use case: Prevents function re-creation when passing functions down to child

components (important when using React.memo or PureComponent).

Example:

const handleClick = useCallback(() => {

// handle the click event

}, [dependencies]); // Recreate the function only when dependencies

change

More from React.js Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details