Careeroza
2. Avoid Unnecessary Re-renders
Techniques
| Technique | Example |
|---|---|
| Keep state local (colocate) | put the search text state in SearchBox, not in App |
| React.memo | memo(ExpensiveChart) |
| useMemo / useCallback | stable props for memo children |
| Split contexts | ThemeContext and UserContext instead of one AppContext |
| Stable keys | key={item.id}, never Math.random() |
| Pass children | slow children passed as children do not re-render with the parent state |
Tip: See Medium → React.memo with useMemo for live examples.
State Colocation Example
Example
Only SearchBox re-renders while typing because the text state lives inside it.
import { useState } from 'react';
function SlowList() {
console.log('SlowList render');
return <ul><li>Item A</li><li>Item B</li></ul>;
}
function SearchBox() {
const [text, setText] = useState(''); // state lives here, not in App
return <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Type: SlowList does not re-render" />;
}
export default function App() {
return (
<div>
<SearchBox />
<SlowList />
</div>
);
}Result