Junior — Middle
What is the difference between functional components and class components in React, and in which cases is it preferable to use them?
sobes.tech AI
Answer from AI
In React, there are two main types of components: class components and functional components.
Class components are components defined as classes that extend React.Component. They have their own state and lifecycle methods.
Functional components are functions that accept props and return JSX. They were previously "static" and did not have state, but with the introduction of hooks, functional components can now use state and other React features.
Differences:
- Class components use
thisto access props and state, while functional components do not. - Functional components are usually shorter and simpler.
- Hooks allow functional components to have state and effects, which was previously only possible in class components.
When to use:
- Preferably use functional components with hooks, as they are simpler, easier to test, and maintain.
- Class components can be used in legacy code or if there are specific requirements, but they are now recommended to be replaced with functional components.
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 with hooks are the modern and recommended way to create components in React.