React Hooks 簡介
React Hooks 是 React 16.8 引入的新特性,讓你在不寫 class 的情況下使用 state 以及其他 React 特性。
核心 Hooks
useState
管理組件內部狀態:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>你點了 {count} 次</p>
<button onClick={() => setCount(count + 1)}>
點我
</button>
</div>
);
}
useEffect
處理副作用操作:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]); // 依賴陣列
return user ? <div>{user.name}</div> : <div>載入中...</div>;
}
useContext
消費 Context:
import React, { useContext } from 'react';
const ThemeContext = React.createContext();
function Button() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background }}>
點我
</button>
);
}
自定義 Hooks
創建可重用的邏輯:
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
}
// 使用
function App() {
const { count, increment, decrement, reset } = useCounter(10);
return (
<div>
<p>計數: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>重置</button>
</div>
);
}
最佳實踐
- 正確使用依賴陣列
- 避免不必要的重新渲染
- 合理拆分 Hooks
- 遵循 Hooks 規則
Hooks 讓 React 開發變得更簡潔和強大!