在 React 中,“無狀態組件(Stateless Component)” 和 “有狀態組件(Stateful Component)” 是兩個非常核心的概念。
理解它們的區別,可以幫助你更好地組織組件、提升可維護性。
什麼是無狀態組件(Stateless Component)
無狀態組件也叫 展示型組件(Presentational Component)。
特點:
- 不管理自己的 state
- 接收 props → 純渲染 UI
- 不處理複雜邏輯
- 通常寫成函數組件
- 相同輸入(props)一定得到相同輸出 → 類似 純函數
示例:無狀態組件
function UserName({ name }) {
return <div>{name}</div>;
}
它沒有內部狀態,也沒有生命週期,只負責展示。
什麼是有狀態組件(Stateful Component)
有狀態組件也叫 容器組件(Container Component)。
特點:
- 自己管理 state
- 包含業務邏輯或數據處理
- 可以使用 Hook(useState、useEffect 等)
- props 改變、state 改變都會觸發重新渲染
示例:有狀態組件
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
這個組件內部擁有自己的狀態,也具有行為邏輯。
無狀態組件 vs 有狀態組件(對比總結)
|
對比項
|
無狀態組件(Stateless)
|
有狀態組件(Stateful)
|
|
是否有 state
|
❌ 沒有
|
✔ 有
|
|
是否有邏輯
|
少
|
多
|
|
是否依賴 props
|
✔ 完全依賴
|
部分依賴
|
|
是否獨立管理數據
|
❌ 不管理
|
✔ 自己管理
|
|
是否更容易複用
|
✔ 是
|
❌ 相對難
|
|
性能
|
🔥 高(通常)
|
較低(要更新 state)
|
|
寫法
|
函數組件(常見)
|
函數組件 + Hook 或 class
|
|
調試、維護
|
簡單
|
相對複雜
|
為什麼要儘量使用無狀態組件?
因為:
- 邏輯更簡單
- 可複用性更高
- 更容易測試
- 渲染更快
- bug 更少
React 的設計理念就是:
把 UI 拆分成儘量多的“無狀態組件”,讓狀態集中管理。
真實項目中的例子
1. 無狀態組件
比如封裝按鈕、Card、Tab 等 UI 展示類組件:
function UserAvatar({ url }) {
return <img src={url} width="40" />;
}
2. 有狀態組件
比如頁面級邏輯組件:
function UserPage() {
const [user, setUser] = useState(null);
useEffect(() => {
fetch("/api/user/1").then(res => setUser(res));
}, []);
return user ? <UserName name={user.name} /> : "Loading...";
}
總結
無狀態組件 = 只展示,不保存數據
有狀態組件 = 存在 state,負責邏輯、數據、交互
實際開發中:
- UI 用無狀態組件
- 頁面或容器用有狀態組件
- 邏輯拆出去放到 hooks(比如 useUser、useFetch)