Why should not we update the state directly?

Technology CommunityCategory: ReactWhy should not we update the state directly?
VietMX Staff asked 3 years ago

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: The only place you can assign the state is constructor.