Jul 2, 2019 in React JS
Q:

Why should we not update the state directly?

2 Answers

0 votes
Jul 2, 2019

If you try to update state directly then it won't re-render the component.

//Wrong
this.state.message = 'Hello world'

Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.

//Correct
this.setState({ message: 'Hello World' })
0 votes
Jan 30

If you try to update state directly then it won't re-render the component.

//Wrong

this.state.message = 'Hello world'

Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.

//Correct

this.setState({ message: 'Hello World' })

Note: You can directly assign to the state object either in constructor or using latest javascript's class field declaration syntax.

Related questions

0 votes
Jul 2, 2019 in React JS
0 votes
Mar 1, 2020 in React JS
...