React Core & Hooks (407 Qs)•General
What are stateful components?
junior LevelCode ExampleComponents
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,
javascript
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>
</>
)
}
The equivalent class stateful component with a state that gets initialized in the constructor:
jsx
import React, { Component } from 'react';
class StatefulCounter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <span>Counter: {this.state.count}</span>;
}
}