Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-render React component after props change

In the React docs, it says

By default, when your component’s state or props change, your component will re-render.

I understand for state changes, but I am not sure about when props change. As far as I am aware, props are always passed from the parent component to the child component. And when the parent component re-renders (due to a state change, for example), all child components also re-render (ignoring shouldComponentUpdate). So it seems to me that if the parent component re-renders, all child components will re-render regardless of whether I am passing new props to them or not. If I do pass new props to the child component, the fact the child re-renders is simply because the parent is re-rendering, not because I am passing new props.

Is there a scenario where a parent component passes new props to a child component, causing the child component to re-render, but it is not caused simply by the parent component re-rendering?

Is it possible to see an example where a component will re-render because it receives new props, rather than because the parent is re-rendering (or its own state changed)?

Sorry if this is a basic question, I am new to React.

EDIT: I see that Redux can cause components to re-render by passing new props, I'm curious to know what Redux is doing behind the scenes to achieve this.

like image 561
ech Avatar asked May 01 '26 10:05

ech


2 Answers

To answer the question you ask at the end:

  • If the child is a PureComponent or wrapped in React.memo it will only re-render if the props change. If the parent re-renders then the component will compare the props it receives and if they're identical to the previously passed props it will not re-render.

  • If the child is not a PureComponent or wrapped in React.memo then it will re-render any time its parent re-renders.

like image 199
Slbox Avatar answered May 03 '26 16:05

Slbox


I‘m not new to react and was asking the same thing. There was an article which made it clear for me: https://thoughtbot.com/blog/react-rendering-misconception

The re-render is needed for diff-checking if DOM updates are necessary. If you‘ve implemented shouldComponentUpdate or wrapped with memo (both returning false), then rerender is skipped.

If a child component is connected using redux or context, then it might rerender even without parent being rerendered.

like image 39
Dennis Avatar answered May 03 '26 18:05

Dennis