Stateless vs Stateful Components
component with state is stateful, and component without state is stateless.
Stateless Component
- Stateless components are easy to use and can be reused in different parts of your app.
- Stateless components, also known as functional components, do not manage or hold any state. They receive data (props) from their parent components and render UI elements based solely on these props.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Stateful component
- Stateful components are more complex and are used to manage state and handle user events.
- Stateful components, also known as class components (or function components with hooks), manage their own state internally. They can handle complex logic, side effects, and interactions.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}