Junior — Middle
What are the main differences between class-based and functional components in React, and what are their advantages and disadvantages?
sobes.tech AI
Answer from AI
Class components in React are components based on ES6 classes that have their own state and lifecycle methods like componentDidMount. Functional components are functions that return JSX. With the advent of hooks, functional components can manage state and side effects.
Advantages of functional components:
- Simpler and shorter to write
- Easier to test
- Use hooks for managing state and effects
- Fewer issues with this
Disadvantages of class components:
- More verbose syntax
- Harder to work with this
Example of a functional component with the useState hook:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Thus, functional components are now preferred for new projects.