Senior
Name the reasons why a React component might be re-rendered.
sobes.tech AI
Answer from AI
A React component can be re-rendered for several reasons:
- Change in props — when the parent component passes new properties.
- Change in state — calling
setStateor updating via hooks likeuseState. - Change in context — if the component subscribes to a context and it changes.
- Forced re-render — calling
forceUpdate. - Change in key — if the component's key changes, React will unmount and mount a new one.
It is also important to note that React by default re-renders a component when the state or props change, even if nothing visually changes. For optimization, you can use React.memo, PureComponent, or hooks like useMemo and useCallback.
Example:
function MyComponent({ value }) {
const [count, setCount] = React.useState(0);
// Re-render occurs when value or count change
return <div>{value} - {count}</div>;
}