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.
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.
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.
xxxxxxxxxx
// Example of a class component with state
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount() {
this.setState((prevState) => ({
count: prevState.count + 1
}));
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={() => this.incrementCount()}>Increment</button>
</div>
);
}
}
ReactDOM.render(<Counter />, document.getElementById('root'));