Middle+
What is useCallback, what does it do, and when should it be used?
sobes.tech AI
Answer from AI
useCallback is a hook in React that returns a memoized version of the callback function that is created inside the component.
What it does:
- Caches the function between renders if dependencies haven't changed.
- Helps avoid creating a new function on every render.
When to use:
- When passing a function to child components that are optimized with
React.memoorshouldComponentUpdateto prevent unnecessary re-renders. - When the function is used in dependencies of other hooks, such as
useEffect, to avoid triggering effects unnecessarily.
Example:
import React, { useState, useCallback } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []); // function does not change between renders
return <button onClick={increment}>Count: {count}</button>;
}
Without useCallback, the increment function would be recreated on every render, which could lead to unnecessary updates of child components.