in Education by
Why should we not update the state directly in React?

1 Answer

0 votes
by

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
    What is the difference between state and props in React?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What is state in React JS?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    How to pass a parameter to an event handler or callback in REACT?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What is the difference between HTML and React event handling?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What are props in React?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What are Pure Components in React js1?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    How to bind methods or event handlers in JSX callbacks?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What is the purpose of callback function as an argument of setState()?...
asked Jun 2, 2021 in General by JackTerrance
0 votes
    When to use a Class Component over a Function Component?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What is the difference between Element and Component?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    What is JSX?...
asked Jun 2, 2021 in Education by JackTerrance
0 votes
    b) List the things we should keep in mind while communicating orally. c) Raghav wants to update the changes in ... customise the TOC? Select the correct answer from above options...
asked Dec 1, 2021 in Education by JackTerrance
0 votes
    I'm new to React with Redux and I've been working on a new web application that has some basic ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 29, 2022 in Education by JackTerrance
0 votes
    Why should we avoid using the training data for evaluation? Please answer the above question....
asked Aug 23, 2022 in Education by JackTerrance
0 votes
    Why should we use Cucumber with Selenium?...
asked Jul 20, 2021 in Technology by JackTerrance
...