HardConcept

Why does a React component re-render and how do you prevent unnecessary re-renders?

Technology:
React
Experience:
Senior

Quick answer

A component re-renders when its state changes, its parent re-renders, or a context it consumes changes; you prevent wasted renders by moving state down, using React.memo, and keeping props referentially stable.

Detailed explanation

By default, when a component renders, all of its children render too, even if their props did not change. React then compares the output and only updates the DOM where something is different, so a re-render is not necessarily a DOM update, but the work of calling your component still costs time.

Start by fixing the structure: keep state close to where it is used, and split a component so a frequently changing part (such as an input) does not drag a heavy sibling along. Passing children as props also helps, because the same element object does not re-render. If that is not enough, wrap pure components in React.memo, stabilise object and function props with useMemo and useCallback, and split large contexts. Use the React DevTools Profiler to confirm what actually rendered and why before optimising.

Key points

  • Triggers: own state change, parent render, context change
  • Move state down and compose with children first
  • React.memo only helps if props are stable
  • ReactMedium

    What is the difference between SSR, SSG and CSR in React?

    CSR renders in the browser after JavaScript loads, SSR renders the HTML on the server for each request, and SSG renders the HTML once at build time; SSR and SSG give crawlers and users content faster, which helps SEO.

    Mid-level 路 Senior 路 Performance
  • ReactEasy

    What is the virtual DOM in React and how does it work?

    The virtual DOM is a lightweight JavaScript copy of the UI that React compares with the previous version after each update, so it only changes the parts of the real DOM that actually differ.

    Intern 路 Junior 路 Performance
  • ReactEasy

    Why do we need keys in React lists?

    Keys give each list item a stable identity so React can match items between renders and correctly add, remove or reorder them without recreating or mixing up their state.

    Junior 路 Mid-level 路 Performance
  • ReactMedium

    What is the difference between useRef and useState in React?

    Updating state triggers a re-render, while changing a ref's .current value does not; use state for data shown on screen and refs for DOM access or values that must persist without causing renders.

    Mid-level 路 Senior 路 React Hooks