useMemo memoizes expensive calculations. useCallback memoizes functions to prevent unnecessary re-renders.
Getting Started
What is React?
Components & Props
Components & Props
Performance & Testing
React.memo & Lazy Loading
Custom Hooks
Building Custom Hooks
Error Boundaries
Error Handling
Server Components
React Server Components
Next.js Introduction
Next.js Basics
Animations & Transitions
Framer Motion
React
Intermediate
FREE
useMemo & useCallback
Lesson 2 of 17
Intermediate
Interactive
Syntax
REACT
const memoizedValue = useMemo(() => computeExpensive(a, b), [a, b]); const memoizedFn = useCallback(() => doSomething(a), [a]);
useMemo and useCallback
REACT
import { useState, useMemo, useCallback } from "react"; function App() { const [count, setCount] = useState(0); const [text, setText] = useState(""); const expensive = useMemo(() => { console.log("Computing..."); return count * 2; }, [count]); const handleClick = useCallback(() => { console.log("Clicked!"); }, []); return ( <div> <p>Doubled: {expensive}</p> <button onClick={() => setCount(c => c + 1)}>Count: {count}</button> <input value={text} onChange={e => setText(e.target.value)} /> </div> ); }
Practice
1
Exercise
Practice this concept.
Answer
Write the code as shown above.
Quick Quiz
1
What did you learn?
This covers the basics.
Interview Questions
It is a fundamental React feature.