The useCallback
hook in React is used to memoize functions, preventing them from being recreated on every render. This can be useful for performance optimization, particularly when passing callback functions to child components that rely on reference equality to prevent unnecessary renders.
useCallback
The useCallback
hook takes two arguments:
The memoized function will only be recreated if one of the dependencies has changed.
import React, { useState, useCallback } from 'react'; const MyComponent = () => { const [count, setCount] = useState(0); const [text, setText] = useState(''); const increment = useCallback(() => { setCount(c => c + 1); }, []); // No dependencies, so this function will never be recreated. const updateText = useCallback((newText) => { setText(newText); }, [text]); // Only recreated if `text` changes. return ( <div> <button onClick={increment}>Increment: {count}</button> <input type="text" value={text} onChange={e => updateText(e.target.value)} /> </div> ); }; export default MyComponent;
useCallback
with Child ComponentsConsider a scenario where you have a parent component passing a callback to a child component. Using useCallback
ensures the callback is not recreated on every render, thus avoiding unnecessary renders of the child component.
// ParentComponent.js import React, { useState, useCallback } from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount(c => c + 1); }, []); return ( <div> <button onClick={increment}>Increment: {count}</button> <ChildComponent onIncrement={increment} /> </div> ); }; export default ParentComponent; </code> </pre> <br> <h5>Child Component</h5> <br> <pre class="version"> // ChildComponent.js import React from 'react'; const ChildComponent = React.memo(({ onIncrement }) => { console.log('Child component rendered'); return ( <div> <button onClick={onIncrement}>Increment from Child</button> </div> ); }); export default ChildComponent;
In this example, the ChildComponent
will only re-render if the onIncrement
function changes. Since useCallback
is used, the onIncrement
function is memoized and only changes if the dependencies (which are none in this case) change.
useCallback
useCallback
to prevent unnecessary re-creation of functions that are passed as props to memoized child components.useCallback
useCallback
for every function. Only use it when you have identified a performance bottleneck related to function creation.