Chapter 16: Performance Optimization

We’ll go very slowly and clearly, with real-world examples you can copy-paste right now — like I’m sitting next to you in Mumbai showing you live on the screen.

1. Memoization with React.memo (Prevent Unnecessary Re-renders of Components)

React.memo is a higher-order component that memoizes (caches) a component. It prevents the component from re-rendering if its props haven’t changed.

When to use:

  • Your component is pure (output depends only on props)
  • It renders often but receives the same props most of the time
  • It’s expensive to render (big lists, heavy JSX, complex calculations)

Example: Expensive Card Component

Create src/components/ExpensiveCard.tsx

tsx

Parent Component (without memo → lots of re-renders)

tsx

Without memo: Every time you click the counter → all 50 cards re-render → console floods with logs + lag With memo: Only the clicked card re-renders → super fast!

2. useMemo & useCallback in Depth (Memoize Values & Functions)

useMemo – Memoize Expensive Calculations

tsx

Key: Only re-calculates when dependencies change.

useCallback – Memoize Functions (Prevent Child Re-renders)

tsx

Without useCallback: Child re-renders every time parent re-renders With useCallback: Child only re-renders if props change → much better performance

3. Code Splitting & Lazy Loading (Load Only What You Need)

Lazy loading = load components only when they are needed (great for big apps).

tsx

Benefits:

  • Smaller initial bundle size
  • Faster first paint
  • Only loads heavy pages when user navigates there

4. React Profiler – Find & Fix Performance Bottlenecks

Wrap slow components with <Profiler> to measure render time.

tsx

Even better: Use React Developer Tools Profiler tab (Chrome/Firefox extension)

  • Record a session
  • See which components are slow
  • Find unnecessary re-renders

Summary – Chapter 16 Key Takeaways

  • React.memo → prevent component re-renders when props same
  • useMemo → memoize expensive values/calculations
  • useCallback → memoize functions (especially callbacks to children)
  • Code splitting + lazy + Suspense → load only what’s needed
  • Profiler → measure & find slow parts
  • Rule of thumb: Memoize when you see unnecessary re-renders in console or lag on interactions

Mini Homework

  1. Take your TodoList or CardList component
  2. Wrap list items with React.memo
  3. Memoize any expensive calculations with useMemo
  4. Memoize event handlers with useCallback
  5. Bonus: Add <Profiler> and check render times in console

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *