Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

How to prevent unnecessary re-renders in React?

Here are several strategies to prevent unnecessary re-renders in React:

  1. Use React.memo for components
    It ensures that functional components only re-render when their props change.

  2. Use useMemo and useCallback hooks

    • useMemo caches the result of expensive calculations.
    • useCallback caches function references, avoiding function recreation on every render.
  3. Avoid anonymous functions and objects in JSX
    Passing inline functions or objects creates new references each render. Instead, define them outside or memoize.

  4. Key props efficiently
    Ensure that lists use stable, unique keys to prevent unnecessary re-mounts.

  5. Split large components
    Break big components into smaller ones, so that only parts of the UI that need updating re-render.

  6. Use pure components (PureComponent or React.memo)
    They perform shallow comparison of props and prevent re-renders if props are unchanged.

Example using useCallback:

const handleClick = useCallback(() => { console.log('Button clicked'); }, []);

This ensures handleClick doesn't get re-created unless its dependencies change.