Minimize re-renders of child component when its parent re-renders, if props didn’t change.
React.memo
import React from 'react';
// Child component wrapped with React.memo
// Only re-render if name changes
const Child = React.memo(({ name }) => {
console.log('Child rendered'); // Helps see when it re-renders
return <div>Child: {name}</div>;
});
// Usage:
export default function App() {
const [count, setCount] = React.useState(0);
const [name, setName] = React.useState('Alice');
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment: {count}</button>
{/* NOT re-render when count changes */}
<Child name={name} />
</div>
);
}
useMemo
import React, { useState, useMemo } from 'react';
function expensiveCalculation(num) {
console.log('Calculating...');
return num * 2; // Imagine heavy calculation here
}
export default function App() {
const [count, setCount] = useState(0);
const [other, setOther] = useState(0);
// useMemo caches the result until `count` changes
const result = useMemo(() => expensiveCalculation(count), [count]);
return (
<div>
<h1>Result: {result}</h1>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
{/* **Change Other** does **not** recompute expensiveCalculation */}
<button onClick={() => setOther(other + 1)}>Change Other</button>
</div>
);
}
// click count button, count state change, whole comp rerender
// u dont want to trigger heavy calc when do simple job
// then remember the expensive one, only recacl when really triggered
useCallback
import React, { useState, useCallback } from 'react';
const Child = React.memo(({ handleClick }) => {
console.log('Child rendered');
return <button onClick={handleClick}>Click Me</button>;
});
export default function App() {
const [count, setCount] = useState(0);
// useCallback ensures function is stable across renders
const handleClick = useCallback(() => {
alert('Clicked!');
}, []);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
{/* Child does **not re-render** when count changes because handleClick is memoized. */}
<Child handleClick={handleClick} />
</div>
);
}
// when click increment button, u want only the count display to rerende
// other no need to change
Problem : Big apps have big JS bundles, causing slow initial load.
<Suspense> handle the “waiting” state