Sobes.tech
Middle+

What causes components to re-render in React?

sobes.tech AI

Answer from AI

In React, a component re-renders when its props or state change. A re-render can also be triggered by a change in context (Context API) or a parent re-render.

Main reasons for re-rendering:

  • Changing state via setState or hooks (useState, useReducer).
  • Receiving new props from a parent component.
  • Changing the value in Context if the component uses it.
  • Forced call of the forceUpdate method.

Example:

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

  // Re-render will occur when count or value change
  return <div onClick={() => setCount(count + 1)}>{value} - {count}</div>;
}

Optimizations include React.memo, useMemo, useCallback to avoid unnecessary re-renders.

What causes components to re-render in React… - sobes.tech