What is better in React? Functional or class component?
Answer
When it comes to choosing between functional and class components in React, it really depends on the specific use case and the needs of the project. Both types of components have their own advantages and disadvantages, and it is important to consider these when making a decision.
Functional components are simpler and easier to read and write. They are also more lightweight and perform better than class components. Functional components are ideal for simple UI components that do not have state or lifecycle methods. They are also great for components that need to be reused frequently, as they are easier to test and maintain.
On the other hand, class components are more feature-rich and powerful. They have access to React's lifecycle methods and can maintain their own internal state. Class components are ideal for complex UI components that require more functionality and state management. They are also useful for components that need to implement certain lifecycle methods or handle user interactions, such as forms.
// Example of a functional component
const MyComponent = () => {
return (
<div>
<p>This is a functional component.</p>
</div>
);
};
// Example of a class component
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
console.log('Component mounted.');
}
render() {
return (
<div>
<p>This is a class component with count {this.state.count}.</p>
</div>
);
}
}
Related React job interview questions
Why do you need to use refs in React?
React JuniorWhat are refs in React?
React JuniorWhat is difference between functional and class component?
React JuniorWhat is class component in React?
React JuniorWhat is functional component in React?
React Junior