Bird
Raised Fist0
Reactframework~8 mins

Avoiding unnecessary renders in React - Performance & Optimization

Choose your learning style10 modes available
Performance: Avoiding unnecessary renders
HIGH IMPACT
This concept affects how fast the UI updates and how responsive the app feels during user interactions.
Rendering a list of items where only some items change
React
const Item = React.memo(function Item({ data }) {
  console.log('Render:', data.id);
  return <div>{data.name}</div>;
});

function ItemList({ items }) {
  return items.map(item => <Item key={item.id} data={item} />);
}
React.memo prevents re-rendering Item components if their props have not changed.
📈 Performance GainReduces re-renders to only changed items, improving responsiveness and lowering CPU load.
Rendering a list of items where only some items change
React
function ItemList({ items }) {
  return items.map(item => <Item key={item.id} data={item} />);
}

function Item({ data }) {
  console.log('Render:', data.id);
  return <div>{data.name}</div>;
}
All Item components re-render whenever the parent ItemList re-renders, even if their data did not change.
📉 Performance CostTriggers N re-renders for N items on every parent update, causing slow UI and high CPU usage.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Without memoizationMany unnecessary DOM updatesMany reflows triggeredHigh paint cost due to frequent updates[X] Bad
With React.memoOnly necessary DOM updatesMinimal reflowsLower paint cost with fewer updates[OK] Good
Rendering Pipeline
When React re-renders a component, it recalculates the virtual DOM and then updates the real DOM if needed. Avoiding unnecessary renders reduces the work in virtual DOM diffing and real DOM updates.
→Virtual DOM Diffing
→Real DOM Update
→Paint
⚠️ BottleneckReal DOM Update is most expensive because it triggers layout and paint.
Core Web Vital Affected
INP
This concept affects how fast the UI updates and how responsive the app feels during user interactions.
Optimization Tips
1Use React.memo to prevent re-renders when props do not change.
2Keep props stable by avoiding inline functions or objects unless memoized.
3Profile your app to find and fix components that render too often.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main benefit of using React.memo for a component?
AIt reduces the bundle size of the app.
BIt makes the component load faster initially.
CIt prevents the component from re-rendering if its props have not changed.
DIt automatically caches API data for the component.
DevTools: React Developer Tools Profiler
How to check: Open the Profiler tab, record while interacting with the component, and observe which components re-render.
What to look for: Look for components that re-render frequently without prop changes; these indicate unnecessary renders.

Practice

(1/5)
1. What is the main purpose of using React.memo in a React component?
easy
A. To convert a class component into a functional component
B. To force the component to re-render every time the parent renders
C. To prevent re-rendering when the component's props have not changed
D. To automatically update the component's state

Solution

  1. Step 1: Understand React.memo's role

    React.memo is a higher-order component that wraps a functional component to optimize rendering.
  2. Step 2: Identify its effect on rendering

    It skips re-rendering the wrapped component if its props remain the same, improving performance.
  3. Final Answer:

    To prevent re-rendering when the component's props have not changed -> Option C
  4. Quick Check:

    React.memo skips renders if props unchanged = D [OK]
Hint: React.memo skips render if props stay the same [OK]
Common Mistakes:
  • Thinking React.memo forces re-render
  • Confusing React.memo with state updates
  • Believing it converts component types
2. Which of the following is the correct syntax to memoize a function using useCallback in React?
easy
A. const memoizedFn = useCallback(() => { doSomething(); }, []);
B. const memoizedFn = useCallback(doSomething(), []);
C. const memoizedFn = useCallback(() => doSomething);
D. const memoizedFn = useCallback(() => { doSomething(); });

Solution

  1. Step 1: Recall useCallback syntax

    useCallback takes a function and a dependency array, returning a memoized version of the function.
  2. Step 2: Check each option's correctness

    const memoizedFn = useCallback(() => { doSomething(); }, []); correctly passes a function and an empty dependency array, memoizing the function properly.
  3. Final Answer:

    const memoizedFn = useCallback(() => { doSomething(); }, []); -> Option A
  4. Quick Check:

    useCallback needs function and dependencies = C [OK]
Hint: useCallback(fn, deps) memoizes function with dependencies [OK]
Common Mistakes:
  • Calling the function inside useCallback instead of passing it
  • Omitting the dependency array
  • Passing function reference without parentheses incorrectly
3. Consider this React component:
const MyComponent = React.memo(({ count, onClick }) => {
  console.log('Rendered');
  return <button onClick={onClick}>Count: {count}</button>;
});

function App() {
  const [count, setCount] = React.useState(0);
  const handleClick = () => setCount(count + 1);
  return <MyComponent count={count} onClick={handleClick} />;
}

What will happen when App re-renders?
medium
A. MyComponent will never re-render because it is wrapped in React.memo
B. MyComponent will re-render every time because handleClick is recreated on each render
C. MyComponent will re-render only when count changes, ignoring onClick
D. MyComponent will re-render only when handleClick changes, ignoring count

Solution

  1. Step 1: Understand React.memo and props

    React.memo skips re-render if props are shallowly equal. Here, onClick is a new function each render.
  2. Step 2: Analyze function recreation

    Since handleClick is recreated on every render, its reference changes, causing MyComponent to re-render.
  3. Final Answer:

    MyComponent will re-render every time because handleClick is recreated on each render -> Option B
  4. Quick Check:

    New function prop breaks memo = B [OK]
Hint: New function props cause re-render despite React.memo [OK]
Common Mistakes:
  • Assuming React.memo ignores function prop changes
  • Thinking React.memo prevents all re-renders
  • Ignoring function identity in props
4. You have this React code that causes unnecessary re-renders:
const Parent = () => {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount(count + 1);
  return <Child onClick={increment} />;
};

const Child = React.memo(({ onClick }) => {
  console.log('Child rendered');
  return <button onClick={onClick}>Click</button>;
});

How can you fix the unnecessary re-renders of Child?
medium
A. Wrap increment in useCallback with count as dependency
B. Remove React.memo from Child
C. Move increment outside the Parent component
D. Use useMemo to memoize count

Solution

  1. Step 1: Identify cause of re-renders

    The increment function is recreated on every render, changing its reference and causing Child to re-render.
  2. Step 2: Apply useCallback to memoize function

    Wrapping increment in useCallback with count dependency keeps the same function reference unless count changes.
  3. Final Answer:

    Wrap increment in useCallback with count as dependency -> Option A
  4. Quick Check:

    Memoize functions with useCallback to avoid re-renders = A [OK]
Hint: Memoize event handlers with useCallback to prevent re-renders [OK]
Common Mistakes:
  • Removing React.memo which disables optimization
  • Moving function outside loses access to state
  • Using useMemo incorrectly for functions
5. You want to optimize a component that receives a large list and a filter function as props. The filter function is defined inline in the parent component. Which approach best avoids unnecessary renders of the child component?
hard
A. Use useMemo to memoize the filtered list inside the child component
B. Define the filter function inline without memoization and rely on React.memo alone
C. Avoid React.memo and always re-render the child component to ensure fresh data
D. Wrap the child component with React.memo and memoize the filter function using useCallback with proper dependencies

Solution

  1. Step 1: Understand props causing re-renders

    The inline filter function changes reference every render, causing child re-renders despite React.memo.
  2. Step 2: Use React.memo and useCallback together

    Wrapping child with React.memo and memoizing the filter function with useCallback keeps function reference stable, avoiding unnecessary renders.
  3. Final Answer:

    Wrap the child component with React.memo and memoize the filter function using useCallback with proper dependencies -> Option D
  4. Quick Check:

    Memoize functions and use React.memo to optimize renders = A [OK]
Hint: Memoize functions and wrap child with React.memo for best optimization [OK]
Common Mistakes:
  • Relying on React.memo without memoizing functions
  • Memoizing filtered list inside child instead of function
  • Avoiding React.memo and causing extra renders
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard