2
votes

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.

4
This is a great question.Yatrix

4 Answers

1
votes

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.

0
votes

When you use provider, or HOC, or Redux with mapStateToProps for example, the props are changed from other component injecting props.

0
votes

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.

0
votes
  1. Connect middleware of redux is similar to subscription, each child component can directly connect to the store through subscription, and whenever the store changes, the store tries to resync all its connected components. New incoming data to any component comes as props resulting in re-render.
  2. Any component getting changed from outside of its state can be through props only, so it is similar to a parent component passing new data / redux store pushing new data to the component.