What is useCallback and why is it used?
useCallback
is a React Hook that memoizes a function so that it only gets recreated when one of its dependencies changes.
const memoizedCallback = useCallback(
() => {
// function body
},
[dependency1, dependency2] // dependencies
);
memoizedCallback
: A function that only updates when dependencies change.dependencies
: Array of variables that trigger recalculation of the function if they change.
Why is it used?
It's primarily used to optimize performance by preventing unnecessary re-creations of functions, especially when those functions are passed as props to child components that use React.memo.