useMemo:
useMemo is a hook in React that memoizes the result of a function so that it is only recomputed when its dependencies change. This can be useful for optimizing performance by avoiding unnecessary calculations or expensive operations.
import React, { useState, useMemo } from 'react';
function MemoExample() {
const [count, setCount] = useState(0);
const squaredValue = useMemo(() => {
return count * count;
}, [count]); // Dependency array: recompute only when 'count' changes
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Count: {count}</p>
<p>Squared Value: {squaredValue}</p>
</div>
);
}
In this example, useMemo is used to calculate the squared value of the count state. It ensures that the squared value is recalculated only when the count state changes, optimizing performance.
useCallback:
useCallback is a hook that memoizes a callback function, similar to useMemo but specifically for functions. It memoizes the callback so that it’s not recreated on every render unless its dependencies change. This can be beneficial for optimizing performance in components that use callback functions, preventing unnecessary re-renders.
import React, { useState, useCallback } from 'react';
function CallbackExample() {
const [text, setText] = useState('');
const handleChange = useCallback((e) => {
setText(e.target.value);
}, []); // Empty dependency array: callback is memoized and does not change
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>Typed Text: {text}</p>
</div>
);
}
Here, useCallback is used to memoize the handleChange callback function. Since the dependency array is empty([]), the callback is memoized and does not change, optimizing performance by avoiding unnecessary function recreations.
0 Comments