React question detail
What are stateful components?
If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are either function components with hooks or class components.
Let's take an example of function stateful component which update the state based on click event,
import React, {useState} from 'react';
const App = (props) => {
const [count, setCount] = useState(0);
handleIncrement() {
setCount(count+1);
}
return (
<>
<button onClick={handleIncrement}>Increment</button>
<span>Counter: {count}</span>
</>
)
}
See Class
The equivalent class stateful component with a state that gets initialized in the constructor.
class App extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleIncrement() {
setState({ count: this.state.count + 1 });
}
render() {
<>
<button onClick={() => this.handleIncrement}>Increment</button>
<span>Count: {count}</span>
</>;
}
}