InterviewHubPRO
Section Overview
Q35

Question 35 of 445

Part 1: Core React, JSX & Component Architecture (1 - 77)

8%
React & Modern Frontend (445 Qs)•Part 1: Core React, JSX & Component Architecture (1 - 77)

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,

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>
</>
)
}
<details><summary><b>See Class</b></summary> <p> The equivalent class stateful component with a state that gets initialized in the `constructor`.
jsx
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>
 </>;
}
}
</p> </details>