Sobes.tech
Middle+

What does a component re-render in React depend on?

sobes.tech AI

Answer from AI

Re-rendering a component in React depends on several factors:

  • Change in props — if the parent passes new properties, the component re-renders.
  • Change in state — calling setState or changing state via hooks (useState) triggers a re-render.
  • Change in context (Context API) — if the context the component subscribes to changes.
  • forceUpdate() — a forced re-render.

React performs a shallow comparison of new and old props and state. If values haven't changed, re-rendering may be skipped (for example, when using React.memo or shouldComponentUpdate).

Example with useState hook:

function Counter() {
  const [count, setCount] = React.useState(0);

  // When setCount is called, the component re-renders
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Thus, re-rendering depends on changes to the component's input data and its internal state.

What does a component re-render in React depend on… - sobes.tech