React useMemo vs useCallback: Understanding the Difference

🚀 One of the most common React interview questions — and most developers answer it wrong. “What’s the difference between useMemo and useCallback?” The most common wrong answer: ❌ “They both prevent re-renders.” Here’s the precise answer: 👉 useMemo caches a computed value 👉 useCallback caches a function reference // useMemo — cache the result of an expensive calculation const sortedList = useMemo(() => { return items.sort((a, b) => a.price - b.price); }, [items]); // useCallback — cache the function itself const handleClick = useCallback(() => { doSomething(id); }, [id]); When to use useMemo: → Expensive calculations (e.g., filtering or sorting large arrays) → Creating objects/arrays passed as props to memoized children When to use useCallback: → Functions passed as props to memoized child components → Functions used in useEffect dependency arrays ⚡ The golden rule: Don’t use either by default. Profile first. Premature memoization adds complexity without real benefit — React is already fast. ✅ Only optimize when you can measure the problem. Curious — what’s the trickiest React hook question you’ve been asked in an interview? 👇 #ReactHooks #JavaScript #FrontendInterview #ReactJS #WebDev

To view or add a comment, sign in

Explore content categories