Skip to main content
InterviewHubPRO
Section Overview
Q318

Question 318 of 407

Part 9: React Hooks Deep Dive (262 - 316)

78%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

Why should we not update the state directly?

mid LevelCode ExampleHooks

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

javascript
   //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.

javascript
   //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.