Why Functions Need Memoization
What you'll learn: Why passing a function as a prop can cause unnecessary re-renders, even when the function's logic hasn't changed.
The Referential Inequality Problem
In JavaScript, every time you define a function inside a component, you're creating a brand new function object—even if the code inside is identical. When React compares values to decide if something has changed, it uses referential equality (===), not whether the code "looks the same."
Here's the key insight: two functions with identical code are not equal:
function Component() {
const handleClick = () => console.log('clicked');
// On every render, this is a NEW function
}
Each render creates a new handleClick with a different memory address. To React, oldHandleClick !== newHandleClick, even though they do exactly the same thing.
Why This Matters
When you pass this function to a child component wrapped in React.memo, or use it in a useEffect dependency array, React sees it as "changed" every single render:
<ExpensiveChild onClick={handleClick} />
// Child re-renders every time, defeating React.memo
Analogy: Imagine you write "Buy milk" on a new sticky note every day. The message is identical, but each note is a different physical object. React can only check if it's the same note, not if it says the same thing.
Key Takeaway
Functions created inside components get a new reference on every render, causing React to treat them as "different" even when their code is identical—this is why we need useCallback to preserve function identity across renders.