Does React re-render all components and their subcomponents whenever "setState()" is invoked?
Yes, React triggers re-rendering by default after "setState()" is called.
Although React aims to optimize rendering, it prevents subtle bugs caused by state mutations by always re-running the "render" method when the state changes.
Each component has a method called "shouldComponentUpdate(nextProps, nextState)". This method determines whether to re-run "render" based on changes to props and state.
By default, "shouldComponentUpdate" returns true, ensuring re-rendering occurs every time the state or props change.
In the provided code snippet, the Main component sets its state to the same value ('me') whenever the text is clicked. Even though the state doesn't change, React still re-renders both the Main and TimeInChild components because "shouldComponentUpdate" returns true by default.
You can optimize rendering by writing a custom implementation of "shouldComponentUpdate" that compares the old and new props and state to determine if an actual re-render is necessary.
The above is the detailed content of Does React Re-render Components After Every `setState()` Call?. For more information, please follow other related articles on the PHP Chinese website!