Q1. What is a class component in React?
A class component is an ES6 class that extends React.Component.
It must contain a render() method that returns JSX.
Class components can have local state and lifecycle methods.
Before hooks, they were the only way to manage state and side effects.
It must contain a render() method that returns JSX.
Class components can have local state and lifecycle methods.
Before hooks, they were the only way to manage state and side effects.
Q2. How do you define state in a class component?
State is defined in the constructor or as a class property.
Example:
State must be updated using
Example:
constructor(props) {
super(props);
this.state = { count: 0 };
}
Or using class fields: state = { count: 0 };State must be updated using
this.setState() to trigger re-rendering.Q3. What are lifecycle methods in class components?
Lifecycle methods are special methods that get called at different stages of a component's life: mounting (componentDidMount), updating (componentDidUpdate), and unmounting (componentWillUnmount).
They allow you to run code at specific times, like fetching data or cleaning up.
They allow you to run code at specific times, like fetching data or cleaning up.
Q4. How do you handle events in class components?
Event handlers are defined as methods on the class.
You need to bind them to the instance in the constructor or use arrow functions.
Example:
You need to bind them to the instance in the constructor or use arrow functions.
Example:
<button onClick={this.handleClick}>Click</button>handleClick = () => { this.setState(...) }
Q5. What is the difference between functional and class components?
Class components use ES6 classes, have lifecycle methods, and use
Functional components are simpler functions that use hooks for state and effects.
Hooks have made functional components more powerful, and they are now the recommended approach in modern React.
this.state/this.setState.Functional components are simpler functions that use hooks for state and effects.
Hooks have made functional components more powerful, and they are now the recommended approach in modern React.
