Mark As Completed Discussion

Updating State

In React, the state of a component can be updated using the setState method. When the state is updated, React triggers a re-render of the component, updating the UI to reflect the new state.

To update the state of a component, you need to:

  1. Access the state object
  2. Modify the desired state property
  3. Call the setState method with the updated state

Here's an example of updating the state in a React class component:

JAVASCRIPT
1class MyComponent extends React.Component {
2  constructor() {
3    super();
4    this.state = {
5      name: 'Maxx',
6      id: '101'
7    };
8  }
9
10  render() {
11    setTimeout(() => {
12      this.setState({
13        name: 'Jaeha',
14        id: '222'
15      });
16    }, 2000);
17
18    return (
19      <div>
20        <h1>Hello {this.state.name}</h1>
21        <h2>Your Id is {this.state.id}</h2>
22      </div>
23    );
24  }
25}
26
27ReactDOM.render(
28  <MyComponent />, document.getElementById('content')
29);

In this example, we define a class component MyComponent with an initial state containing name and id properties. Inside the render method, we use the setTimeout function to update the state after 2 seconds.

The setState method is called with an object containing the updated state values. React then re-renders the component, displaying the updated state values in the UI.

Try running the code above and observe how the state updates and triggers a re-render after 2 seconds.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment