Middle+
What mechanisms cause a component to re-render in React?
sobes.tech AI
Answer from AI
A React component re-renders in the following cases:
- When the component's state changes via
setStateor theuseStatehook. - When the props passed to the component change.
- When the context changes, if the component is subscribed to React Context.
- When the parent component calls itself, leading to a re-render of child components.
To optimize rendering, you can use React.memo for functional components or shouldComponentUpdate in class components to prevent unnecessary re-renders when data hasn't changed.
Example with the useState hook:
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Each call to setCount triggers a re-render of the component.