Clean β’ Professional
In React, functional components re-render whenever their state or props change. This means that functions defined inside components are re-created on every render, which can lead to unnecessary re-renders of child components if these functions are passed as props.
The useCallback hook solves this by caching a function so that its reference remains stable between renders unless its dependencies change. This is a key tool for performance optimization in React apps.
useCallback?useCallback is a React hook that returns a memoized version of a function, preventing its re-creation on every render.
Syntax:
const memoizedFunction = useCallback(() => {
// function logic
}, [dependencies]);
memoizedFunction β The cached function reference[dependencies] β Array of variables; the function updates only if these changeReact.memo().Example:Β
import React, { useState, useCallback } from "react";
const Button = React.memo(({ handleClick, label }) => {
console.log(`Rendering Button: ${label}`);
return <button onClick={handleClick}>{label}</button>;
});
function App() {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
// Memoized function
const increment = useCallback(() => {
setCount(c => c + 1);
}, []); // Function remains the same until dependencies change
return (
<div>
<h1>Count: {count}</h1>
<Button handleClick={increment} label="Increment" />
<inputtype="text"
value={text}
onChange={e => setText(e.target.value)}
placeholder="Type something..."
/>
</div>
);
}
export default App;
increment function is memoized, so Button does not re-render unnecessarily when text changes.useCallback, increment would be re-created on every render, causing Button to re-render even if its props havenβt changed.useCallback with DependenciesWhen a memoized function depends on other variables, include them in the dependency array:
const incrementBy = useCallback(() => {
setCount(count + 1);
}, [count]); // Updates function if 'count' changes
count changes.