Stateful components are those components in react that manage their own state, allowing them to dynamically update the UI based on changes in data or user interactions. The state is stored within the component's state object.
The state in a component is an object that holds data that might change during the lifecycle of the component. This information changes as the component is used.
It can be accessed via this.state in class components or with the useState hook in functional components.
In class components, you update the state using this.setState().
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
In functional components, you update state by calling the updater function returned by useState.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;