The UseCallback Hook.
The Basics
useCallback(fn, dependencies)
Right. Let's do this.
React does too much. Every time your component re-renders, everything inside of it (including your functions) are re-created.
Even if your function hasn't changed, React sees a "new" version on every render.
Usually, this isn't an issue, but it becomes an issue when you're passing the function down to a child that's trying to maintain efficiency.
The problem: Without useCallback, a child component might re-render unnecessarily because it thinks it received a "brand new" function from the parent, even if nothing actually changed.
The solution: useCallback Ensures the function maintains the same "identity" across renders.
What's the difference between useCallback and useMemo?
useMemo Memoises (remembers) the result or the value returned by a function.
function AdditionComponent(firstNumber, secondNumber) {
const additionResult = useMemo(() => {
return firstNumber + secondNumber;
}, [firstNumber, secondNumber]);
}
In this case, useMemo will cache the value returned by the additionResult function. So if firstNumber = 1 and secondNumber = 2, the cached result will be 3.
useCallback remembers (caches) the function itself.
function AdditionComponent(firstNumber, secondNumber) {
const handleAddition = useCallback(() => {
return firstNumber + secondNumber;
}, [firstNumber, secondNumber]);
}
In this case, useCallback caches the function itself, and will only re-create the function if either of its dependencies (firstNumber or secondNumber) change.
function AdditionComponent(firstNumber, secondNumber) {
const additionResult = useMemo(() => {
return firstNumber + secondNumber
}, [firstNumber, secondNumber]);
}
Note: useCallback is essentially just a specific implementation of useMemo, designed only to store functions. Caching a value? Use useMemo. Caching a function? Use useCallback
With Typescript
Great news! You don't need to explicitly type this.
useCallback also uses type inference (noticing a pattern, yet?).