2. Avoid Unnecessary Re-renders

Techniques

TechniqueExample
Keep state local (colocate)put the search text state in SearchBox, not in App
React.memomemo(ExpensiveChart)
useMemo / useCallbackstable props for memo children
Split contextsThemeContext and UserContext instead of one AppContext
Stable keyskey={item.id}, never Math.random()
Pass childrenslow 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