useCallback(): This React hook is used to cache (memoize) a function. It remembers the function, so the reference doesn't change unless the dependencies do. This does not run the function; it only remembers it.
example: Lets take this password generator code.
const passwordGenerator = useCallback(() => {
let pass = "";
let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (numberAllowed) str += "0123456789";
if (charAllowed) str += "!@#$%^&*(){}[]~`-";
for (let i = 0; i < length; i++) {
let char = Math.floor(Math.random() * str.length);
pass += str.charAt(char);
}
setPassword(pass);
}, [length, numberAllowed, charAllowed]);
Whenever any dependencies from
[length, numberAllowed, charAllowed]
This dependency array changes, Only values of these dependencies within the function changes Note: The function is memoized (not recreated) unless dependencies change. But it still runs if you call it explicitly, like we did inside useEffect
So, we can say that useCallback is used for performance optimization. It memoizes the function to avoid unnecessary re-creations, and it will only be re-created when the dependencies change—not just on every render.
useEffect(): This React hook is used to run functions or side effects after the render when dependencies change. It can be understood as something changing when the count changes.
in this example side Effect passwordGenerator() whenever a dependency changes from dependency array.
useEffect(()=>{
passwordGenerator();
},[length,passwordGenerator,numberAllowed,charAllowed,]);
In this case:
useEffect runs after render.
It calls the memoized passwordGenerator() function.
The effect re-runs whenever any dependency changes: length, numberAllowed, charAllowed, or the function itself (though it's memoized, React still tracks it for safety
useEffect() is a React Hook used to run side effects in a component, such as:
It runs the callback after the component renders and whenever the dependencies in its array change.
🔁 Summary
| Hooks |
Purpose |
Runs when |
useCallback |
Memoizes a function |
Dependencies change |
useEffect |
Runs a side-effect after render |
Dependencies change (or on mount if empty |