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
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png