score:652
Does React re-render all components and sub-components every time setState is called?
By default - yes.
There is a method boolean shouldComponentUpdate(object nextProps, object nextState), each component has this method and it's responsible to determine "should component update (run render function)?" every time you change state or pass new props from parent component.
You can write your own implementation of shouldComponentUpdate method for your component, but default implementation always returns true - meaning always re-run render function.
Quote from official docs http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate
By default, shouldComponentUpdate always returns true to prevent subtle bugs when the state is mutated in place, but if you are careful to always treat the state as immutable and to read-only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.
Next part of your question:
If so, why? I thought the idea was that React only rendered as little as needed - when the state changed.
There are two steps of what we may call "render":
Virtual DOM renders: when render method is called it returns a new virtual dom structure of the component. As I mentioned before, this render method is called always when you call setState(), because shouldComponentUpdate always returns true by default. So, by default, there is no optimization here in React.
Native DOM renders: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.
score:0
Regardless of the well explained answers here, there may be other reasons why you don't see the change you expect post changing the props or state:
Watch out for any event.preventDefault();
in the code where you want to re-render by a state \ props change, as it will cancel any cancelable event following this statement.
score:0
You could use setState() only after comparing the current state value and the new one and they are different.
score:1
Not All Components.
the state
in component looks like the source of the waterfall of state of the whole APP.
So the change happens from where the setState called. The tree of renders
then get called from there. If you've used pure component, the render
will be skipped.
score:2
React 18 and beyond
Starting from React 18 all state updates are automatically batched to groups multiple state updates into a single re-render for better performance.
So when you update your state, React always try to batch these updates in a group update, causing fewer render than setState
calls. The behaviour is the same when using hooks.
You can read the very long explanation in the Automatic batching for React 18 announcement.
React 17 and below
In React 17 and below, only updates inside React event handlers are batched. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default.
score:4
Another reason for "lost update" can be the next:
- If the static getDerivedStateFromProps is defined then it is rerun in every update process according to official documentation https://reactjs.org/docs/react-component.html#updating.
- so if that state value comes from props at the beginning it is overwrite in every update.
If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this
static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}
Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)
score:6
It seems that the accepted answers are no longer the case when using React hooks (with primitive values, see comments on this answer for details). You can see in this code sandbox that the class component is rerendered when the state is set to the same value, while in the function component, setting the state to the same value doesn't cause a rerender.
score:10
Yes. It calls the render()
method every time we call setState
only except when shouldComponentUpdate
returns false
.
score:11
Even though it's stated in many of the other answers here, the component should either:
implement
shouldComponentUpdate
to render only when state or properties changeswitch to extending a PureComponent, which already implements a
shouldComponentUpdate
method internally for shallow comparisons.
Here's an example that uses shouldComponentUpdate
, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.
var TimeInChild = React.createClass({
render: function() {
var t = new Date().getTime();
return (
<p>Time in child:{t}</p>
);
}
});
var Main = React.createClass({
onTest: function() {
this.setState({'test':'me'});
},
shouldComponentUpdate: function(nextProps, nextState) {
if (this.state == null)
return true;
if (this.state.test == nextState.test)
return false;
return true;
},
render: function() {
var currentTime = new Date().getTime();
return (
<div onClick={this.onTest}>
<p>Time in main:{currentTime}</p>
<p>Click me to update time</p>
<TimeInChild/>
</div>
);
}
});
ReactDOM.render(<Main/>, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
score:130
No, React doesn't render everything when the state changes.
Whenever a component is dirty (its state changed), that component and its children are re-rendered. This, to some extent, is to re-render as little as possible. The only time when render isn't called is when some branch is moved to another root, where theoretically we don't need to re-render anything. In your example,
TimeInChild
is a child component ofMain
, so it also gets re-rendered when the state ofMain
changes.React doesn't compare state data. When
setState
is called, it marks the component as dirty (which means it needs to be re-rendered). The important thing to note is that althoughrender
method of the component is called, the real DOM is only updated if the output is different from the current DOM tree (a.k.a diffing between the Virtual DOM tree and document's DOM tree). In your example, even though thestate
data hasn't changed, the time of last change did, making Virtual DOM different from the document's DOM, hence why the HTML is updated.
Source: stackoverflow.com
Related Query
- ReactJS - Does render get called any time "setState" is called?
- ReactJs - Does not render the updates after setState is called
- In React why does a child component's render function get called twice?
- onClick function called at render time in ReactJS
- Component does not get called in mapping ReactJS
- Sharing on social media, the URL does not render any meta data
- Any way to get Context value in component constructor method in ReactJS
- In ReactJS trying to get params but I get property 'id' does not exist on type '{}'
- All React-bootstrap Tabs render function gets called every time regardless of which tab was selected
- componentDidMount seems not to be called after setState in ReactJS
- setState called in render prop is causing a react warning
- Typescript + Reactjs - Imported svg does not render
- reactjs try catch in render does not catch children errors
- setstate inside render method - Reactjs
- Table in react-virtualized does not render any rows
- reactjs setState before render on update
- Stop function from being called on Render EVERY TIME
- Does removing unused imports have an impact on bundle size and build time in Reactjs
- How does ReactJS evaluate any JavaScript Expression inside JSX?
- How to get ReactJS to render empty HTML attributes
- Reactjs every time refreshing page on setState
- How to use React.useContext in a function that does not render any components?
- ReactJS context-api won't render after I get data
- Default props are not available in first time render ReactJS
- Why does the render function in react is called twice when using the component strategy?
- ReactJS - SetState does not update the state when the state variable is a number
- Nextjs: Render data from GET request each time the page loads
- ReactJS - button onClick gets called during render
- Why does React render component for the second time after setting the state to the same value?
- what is the point of having static propTypes in reactjs and does it solve any problem or is it just a pattern
More Query from same tag
- BrowserRouter doesnt accept child routes passed as props
- Firebase Web - Signout - Cannot delete property '0' of [object Array]
- How to style 'disabled' class in TextField in Material UI 5 using global CreateTheme?
- How can I avoid unnecessary re rendering of an HOC component, when the parameter component renders in ReactJS with react router
- How to preload third-party's css and js files using webpack in ReactJS project?
- How to customize both, width of the bar & spacing between bar in Highcharts.js
- React setState is null
- Issue with rendering component
- HTTPS on localhost using NextJS + Express
- React Function Calling Methods
- Cant use uuid4 in react-native
- Custom Loader does not get applied with respect to react-table
- React Material UI can't find mobile device on first render
- How to implement link in draft.js?
- how to handle useEffect with render props in react
- How to import bundle created in webpack?
- React JS .map returns all data the same times as objects in JSON
- Ant Design Pro: how to redirect route keeping query parameters
- React error when removing input component
- unable to do redirect from login to dashboard
- Relative image paths from js object in React
- Webpack babel-loader es2015 presets setting is not working
- Accessing local json files from the browser using NodeJs backend
- Editor.js rendering/outputting two editors in React
- Cannot find type definition file for 'node' in Typescript/React app
- Best input type to record a time Duration in Html
- How to correctly make side effects during rendering on functional components?
- How to display Material-ui Alert based on the response of axios.post reactjs
- How do I get the value when using useState outside of the function?
- How to change the property of an object inside an array propertly in react