In React, components are the building blocks of your UI. One key concept that every developer should understand early on is the difference between stateful and stateless components. This distinction plays a big role in how your application behaves and how maintainable your code is.
π What Is a Stateful Component?
A stateful component is a component that manages its own local state using hooks like useState
or useReducer
.
Key Characteristics:
- Holds and updates state internally.
- Reacts to user interactions or lifecycle events.
- Re-renders when the state changes.
Example:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
This Counter
component tracks and updates a count. Itβs stateful because it uses useState
.
What Is a Stateless Component?
A stateless component is a pure function. It receives data (props) and returns UI based on those props. It doesn't manage any state or side effects internally.
Key Characteristics:
- Has no local state.
- Pure function: same input always gives the same output.
- Used for UI rendering only.
Example:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
This Greeting
component simply displays the name it receives. No internal logic β just UI. Itβs stateless.
Why Separate State from UI?
Separating stateful logic from presentation improves:
- Code reusability: Stateless components are easier to reuse.
- Testability: Pure functions are simpler to test.
- Readability: Clearer separation of concerns.
A common practice is to extract state management and side effects (like data fetching) into custom hooks or container components and keep UI components as stateless as possible.
Summary Table
Feature | Stateful Component | Stateless Component |
---|---|---|
Holds local state | β Yes | β No |
Triggers re-renders | β When state changes | β When props change |
Reusability | π‘ Less reusable (tied to logic) | β More reusable |
Testability | π‘ Slightly more complex | β Easy to test (pure) |
Top comments (0)