Mark As Completed Discussion

State and Lifecycle

In React, components can have state, which is an object that contains data that can change over time. State allows you to manage and control the data within a component.

To use state in a class component, you need to initialize it in the constructor method. The initial state is typically set as an object with key-value pairs, where each key represents a piece of data and each value represents its initial value.

SNIPPET
1// Example of a class component with state
2
3class Counter extends React.Component {
4  constructor(props) {
5    super(props);
6    this.state = {
7      count: 0
8    };
9  }
10
11  render() {
12    return (
13      <div>
14        <h1>Count: {this.state.count}</h1>
15        <button onClick={/* incrementCount logic */}>Increment</button>
16      </div>
17    );
18  }
19}

In the above example, the Counter component has a state property count with an initial value of 0. The state is accessed in the JSX using this.state.<key>. Any changes to the state should be made using the setState method, which triggers a re-render of the component.

To modify the state, you can define methods within the class component that update the state using setState. In the example above, the incrementCount method is defined to increment the count state value by 1.

JAVASCRIPT
1console.log("Managing component state and lifecycle methods");

This is just a basic introduction to state in React. In subsequent lessons, we will explore more about state and how it can be updated and managed in different scenarios.

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