How do you optimize performance in React apps?

πŸ’‘ Concept Name

React Performance Optimization involves improving app speed and responsiveness by reducing unnecessary rendering, optimizing resource usage, and applying best practices like memoization and lazy loading.

πŸ“˜ Quick Intro

React apps can become slow due to frequent re-renders or large component trees. Techniques like memoization, code-splitting, and proper state management help improve performance and user experience.

🧠 Analogy / Short Story

Think of optimizing a React app like maintaining a smart city: only turn on streetlights when needed (lazy loading), avoid repeating the same announcements (memoization), and reroute traffic only when roads change (efficient re-renders). This ensures smooth operations and faster responses.

πŸ”§ Technical Explanation

  • 🧠 Use React.memo to prevent re-rendering components that receive the same props.
  • ⚑ Apply useCallback and useMemo to memoize functions and values.
  • πŸ›‘ Avoid passing new props unnecessarily to child components.
  • πŸ“¦ Code-split using React.lazy and Suspense.
  • πŸ“ˆ Use virtualization libraries like react-window for large lists.
  • 🧹 Remove unused state, dependencies, or large libraries.
  • πŸ§ͺ Use Profiler and DevTools to detect performance bottlenecks.

πŸ’» Real Code Example


import React, { memo, useMemo, useCallback } from 'react';

const ExpensiveComponent = memo(({ data }) => {
  console.log('Rendering ExpensiveComponent');
  return <div>{data}</div>;
});

function App() {
  const data = useMemo(() => computeExpensiveValue(), []);
  const handleClick = useCallback(() => alert('Clicked'), []);

  return (
    <div>
      <ExpensiveComponent data={data} />
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}

function computeExpensiveValue() {
  // simulate a CPU-intensive task
  return 'Expensive Result';
}

❓ Interview Q&A

Q1: What is the purpose of React.memo?
A: It prevents unnecessary re-renders of functional components by memoizing them based on props.

Q2: How does useCallback help in performance?
A: It memoizes a callback so the function identity stays the same between renders.

Q3: What is code-splitting in React?
A: Loading parts of the application only when needed using React.lazy.

Q4: How can you optimize large lists in React?
A: Use windowing libraries like react-window or react-virtualized.

Q5: What tools help identify performance issues?
A: React DevTools, Profiler tab, Lighthouse, and Chrome Performance tab.

Q6: What does useMemo do?
A: Caches the result of a function so it only recomputes when dependencies change.

Q7: Should you always use useMemo and useCallback?
A: No, use them only when they bring measurable performance gains.

Q8: How can too much state affect performance?
A: State changes can cause unnecessary re-renders if not scoped properly.

Q9: What's the impact of anonymous functions in JSX?
A: They create new function instances on each render, possibly triggering re-renders.

Q10: When should you avoid React.memo?
A: When the component is simple or the overhead of comparison outweighs the re-render cost.

πŸ“ MCQs

Q1. Which hook memoizes a value?

  • useState
  • useEffect
  • useMemo
  • useRef

Q2. What does React.memo do?

  • Manages state
  • Prevents re-renders
  • Creates context
  • Triggers effects

Q3. Which tool helps find performance issues?

  • React Router
  • React Profiler
  • Babel
  • Redux DevTools

Q4. Which library is best for virtualizing lists?

  • axios
  • react-router
  • react-window
  • formik

Q5. How do you load components lazily?

  • setTimeout
  • React.memo
  • React.lazy
  • useReducer

Q6. Why use useCallback?

  • Run async code
  • Bind context
  • Memoize functions
  • Trigger render

Q7. What’s a downside of anonymous functions in JSX?

  • Memory leak
  • Syntax error
  • New instance each render
  • Style issues

Q8. When does useMemo recompute?

  • Every render
  • Never
  • When component mounts
  • When dependencies change

Q9. What causes unnecessary re-renders?

  • Static content
  • Same state
  • New prop references
  • Pure functions

Q10. Should useMemo be used everywhere?

  • Yes
  • No, only when beneficial
  • Always
  • Never

πŸ’‘ Bonus Insight

Performance optimization is best approached with measurement tools. Don't blindly optimizeβ€”profile first, then apply the right technique based on real usage patterns.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: