Slide 1
-----------
Part 1: The useCallback hook in React is used to memoize functions so that they are not recreated on every render. This helps in optimising performance, especially in scenarios where the function is passed as a prop to child components or used in expensive computations.
Slide 2
-----------
Part 1: Every time a component re-renders, all its functions are recreated, even if their logic hasn’t changed. This can lead to unnecessary re-renders of child components or performance issues in complex apps. By memoizing a function with useCallback, you ensure the function retains its identity unless its dependencies change.
Slide 3
-----------
Part 1: useCallback returns the same function instance as long as the dependencies don’t change. When dependencies change, a new function is created.
Slide 4
-----------
Part 1: Here’s an example of how useCallback can prevent unnecessary re-renders.
Part 2: Parent re-renders on the Increment button click.
Part 3: Every time the Parent re-renders (when count changes), the handleClick function is recreated.
Part 4: Even though Child is a pure component, this causes the Child component to re-render unnecessarily, as the onClick handler is a new function, albeit doing the same functionality as its previous version.
Part 5: Therefore we need to make sure that this callback is not recreated unnecessarily.
Part 6: For this, we apply the useCallback hook and memoise the handleClick function.
Part 7: When we click the button, the Child component doesn’t re-render unless handleClick changes, which happens only if its dependencies change (none in this case).
Slide 5
-----------
Part 1: When a function depends on state or props, you can include them in the dependency array.
Part 2: The handleClick function is recreated only when the count changes, ensuring it always logs the latest value of the count.
Part 3: Clicking on the Increment button re-renders child
Part 4: But logging displays the correct value. Try removing the count from the dependency variables and guess what happens!
Slide 6
-----------
Part 1: useCallback can help optimise your app. Use it when passing Functions as Props to prevent unnecessary re-renders of memoized child components.
Part 2: Also, to optimise frequently used handlers like onClick, onChange, etc.
Part 3: Or to memoize expensive functions that are called repeatedly in the render cycle.
Slide 7
-----------
Part 1: But useCallback comes with small performance overhead and it also makes your code harder to read. Therefore, do not overuse this hook, and don’t wrap every function in useCallback. Use it only when there’s a clear performance benefit.
Part 2: Remember that in small apps, function recreation is rarely a performance bottleneck.
Slide 8
-----------
Part 1: To summarise ...
Part 2: The purpose of useCallback is to memoize functions to prevent unnecessary re-creations and improve performance.
Part 3: The syntax of use callback is defined by the callback function and a list of dependencies defining when to re-create this callback
Part 4: The key use case is to prevent child re-renders, optimize event handlers, and memoise expensive functions.
Part 5: But, use it judiciously; overuse can complicate code without significant benefits..
UNDERSTANDING USECALLBACK IN REACT
The useCallback hook in React is used to memoize functions so that they are not
recreated on every render. This helps in optimizing performance, especially in
scenarios where the function is passed as a prop to child components or used in
expensive computations.
--------------------------------------------------------------------------------
WHY USECALLBACK?
Every time a component re-renders, all its functions are recreated, even if
their logic hasn’t changed. This can lead to:
1. Unnecessary re-renders of child components.
2. Performance issues in complex apps.
By memoizing a function with useCallback, you ensure the function retains its
identity unless its dependencies change.
--------------------------------------------------------------------------------
HOW USECALLBACK WORKS
const memoizedCallback = useCallback(() => {
// Your function logic here
}, [dependencies]);
* useCallback returns the same function instance as long as the dependencies
don’t change.
* When dependencies change, a new function is created.
--------------------------------------------------------------------------------
KEY USE CASES
1. Preventing unnecessary renders of child components.
2. Optimizing event handlers in large or complex components.
--------------------------------------------------------------------------------
BASIC EXAMPLE
Here’s an example of how useCallback can prevent unnecessary re-renders:
WITHOUT <STRONG>USECALLBACK</STRONG>:
import React, { useState } from "react";
const Child = React.memo(({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click Me</button>;
});
const Parent = () => {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Button clicked");
};
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child onClick={handleClick} />
</div>
);
};
export default Parent;
Behavior:
* Every time the Parent re-renders (when count changes), the handleClick
function is recreated.
* This causes the Child component to re-render unnecessarily, even though its
props haven’t changed.
--------------------------------------------------------------------------------
WITH <STRONG>USECALLBACK</STRONG>:
jsx
Copy code
import React, { useState, useCallback } from "react";
const Child = React.memo(({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click Me</button>;
});
const Parent = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []); // No dependencies, so the function is memoized and won't change
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child onClick={handleClick} />
</div>
);
};
export default Parent;
Behavior:
* The handleClick function is memoized using useCallback.
* The Child component doesn’t re-render unless handleClick changes, which
happens only if its dependencies change (none in this case).
--------------------------------------------------------------------------------
ADVANCED EXAMPLE: WITH DEPENDENCIES
When a function depends on state or props, you can include them in the
dependency array.
const Parent = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log(`Count: ${count}`);
}, [count]); // Recreate the function only if `count` changes
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={handleClick}>Log Count</button>
</div>
);
};
Behavior:
* The handleClick function is recreated only when count changes, ensuring it
always logs the latest value of count.
--------------------------------------------------------------------------------
WHEN TO USE USECALLBACK
1. Passing Functions as Props:
* Prevent unnecessary re-renders of memoized child components.
2. Event Handlers:
* Optimize frequently used handlers like onClick, onChange, etc.
3. Expensive Functionality:
* Memoize expensive functions that are called repeatedly in the render
cycle.
--------------------------------------------------------------------------------
WHEN NOT TO USE USECALLBACK
* Overuse: Don’t wrap every function in useCallback. Use it only when there’s a
clear performance benefit.
* Simple Apps: In small apps, function recreation is rarely a performance
bottleneck.
--------------------------------------------------------------------------------
SUMMARY
* Purpose: Memoize functions to prevent unnecessary re-creations and improve
performance.
* Syntax: useCallback(() => {...}, [dependencies])
* Key Use Cases: Prevent child re-renders, optimize event handlers, memoize
expensive functions.
* Caution: Use it judiciously; overuse can complicate code without significant
benefits.
Let me know if you’d like a deeper dive or more examples! 🚀
Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.
Join the discussion to ask questions, share your thoughts, and discuss with other learners