Middle
Have you found a use for useCallback?
sobes.tech AI
Answer from AI
useCallback is a hook in React that allows memoizing a function so that it is not recreated on every component render. This is useful when passing the function to child components, especially those optimized with React.memo, or when the function is used in dependencies of other hooks, such as useEffect.
Example of usage:
import React, { useState, useCallback } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []); // the function does not change on re-renders
return <Child onClick={increment} count={count} />;
}
const Child = React.memo(({ onClick, count }) => {
console.log('Child render');
return <button onClick={onClick}>Count: {count}</button>;
});
Here, useCallback prevents unnecessary re-renders of Child, as the reference to the increment function does not change.