簡介
beautiful-react-hooks
?是一個專為 React 設計的高質量自定義 Hooks 集合,涵蓋了事件、狀態、生命周期、DOM 操作、性能優化等多個方面,極大提升了函數組件的開發效率和代碼復用性。
安裝方法
npm install beautiful-react-hooks
# 或
yarn add beautiful-react-hooks
常用 Hook 分類與詳解
useToggle —— 布爾值/任意值切換
import useToggle from "beautiful-react-hooks/useToggle";export default function BeautifulHooks() {const [on, toggle] = useToggle(false);return (<div className="container p-4"><buttononClick={toggle}className={`px-4 py-2 rounded mb-2 text-white font-medium transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400 ${on ? "bg-green-500 hover:bg-green-600" : "bg-red-500 hover:bg-red-600"}`}>{on ? "開關已打開" : "開關已關閉"}</button><div className="mt-2 text-base">當前狀態:<b className={on ? "text-green-600" : "text-red-600"}>{on ? "ON" : "OFF"}</b></div></div>);
}
usePreviousValue —— 獲取前一個值
import useToggle from "beautiful-react-hooks/useToggle";
import usePreviousValue from "beautiful-react-hooks/usePreviousValue";export default function BeautifulHooks() {const [on, toggle] = useToggle(false);const prevOn = usePreviousValue(on);return (<div className="container p-4"><buttononClick={toggle}className={`px-4 py-2 rounded mb-2 text-white font-medium transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400 ${on ? "bg-green-500 hover:bg-green-600" : "bg-red-500 hover:bg-red-600"}`}>{on ? "開關已打開" : "開關已關閉"}</button><div className="mt-2 text-base">當前狀態:<b className={on ? "text-green-600" : "text-red-600"}>{on ? "ON" : "OFF"}</b></div><div className="mt-1 text-sm text-gray-500">上一次狀態:<b className={prevOn ? "text-green-600" : "text-red-600"}>{prevOn === undefined ? "無" : prevOn ? "ON" : "OFF"}</b></div></div>);
}
useObjectState —— 對象狀態管理
import useObjectState from "beautiful-react-hooks/useObjectState";export default function BeautifulHooks() {const [form, setForm] = useObjectState({ name: "", age: "" });return (<div className="container p-4"><div className="mt-6 p-4 border rounded bg-gray-50"><div className="mb-2 font-semibold">useObjectState 示例</div><div className="flex flex-col gap-2"><inputclassName="border px-2 py-1 rounded focus:outline-none focus:ring-2 focus:ring-blue-400"type="text"placeholder="姓名"value={form.name}onChange={(e) => setForm({ name: e.target.value })}/><inputclassName="border px-2 py-1 rounded focus:outline-none focus:ring-2 focus:ring-blue-400"type="number"placeholder="年齡"value={form.age}onChange={(e) => setForm({ age: e.target.value })}/></div><div className="mt-2 text-sm text-gray-700">當前表單狀態:<span className="font-mono">{JSON.stringify(form)}</span></div></div></div>);
}
useValidatedState —— 校驗型狀態
import useValidatedState from "beautiful-react-hooks/useValidatedState";export default function BeautifulHooks() {// 校驗函數:密碼長度大于3const passwordValidator = (password) => password.length > 3;const [password, setPassword, validation] = useValidatedState(passwordValidator,"");return (<div className="container p-4"><div className="mb-2 font-semibold">useValidatedState 示例</div><inputclassName={`border px-2 py-1 rounded focus:outline-none focus:ring-2 focus:ring-blue-400 w-64 ${!validation.valid ? "border-red-500" : ""}`}type="password"placeholder="請輸入密碼(大于3位)"value={password}onChange={(e) => setPassword(e.target.value)}/><div className="mt-2 text-sm">{validation.valid ? (<span className="text-green-600">密碼合法</span>) : (<span className="text-red-500">密碼太短</span>)}</div></div>);
}
useEvent —— 事件回調
import { useState, useRef } from "react";
import useEvent from "beautiful-react-hooks/useEvent";export default function BeautifulHooks() {const targetRef = useRef();const [clicksNo, setClicksNo] = useState(0);const onTargetClick = useEvent(targetRef, "click");onTargetClick(() => {setClicksNo((c) => c + 1);});return (<div className="container p-4"><div className="mb-2 font-semibold">useEvent 示例</div><divref={targetRef}className="p-4 border rounded cursor-pointer select-none hover:bg-blue-50 text-gray-800">點擊此文本增加計數:{clicksNo}</div></div>);
}
useGlobalEvent —— 全局事件監聽
import { useState } from "react";
import useGlobalEvent from "beautiful-react-hooks/useGlobalEvent";export default function BeautifulHooks() {const [windowWidth, setWindowWidth] = useState(window.innerWidth);const onWindowResize = useGlobalEvent("resize");onWindowResize(() => {setWindowWidth(window.innerWidth);});return (<div className="container p-4"><div className="mb-2 font-semibold">useGlobalEvent 示例</div><div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded text-blue-800">調整瀏覽器窗口大小以更新狀態</div><div className="p-4 border rounded bg-gray-50 text-gray-800">window width:{" "}<span className="inline-block px-2 py-1 bg-green-100 text-green-700 rounded font-mono">{windowWidth}</span></div></div>);
}
useWindowResize —— 監聽窗口尺寸變化
import useWindowResize from "beautiful-react-hooks/useWindowResize";
import { useState } from "react";export default function BeautifulHooks() {const [size, setSize] = useState({width: window.innerWidth,height: window.innerHeight,});useWindowResize(() => {setSize({ width: window.innerWidth, height: window.innerHeight });});return (<div className="container p-4"><div className="mb-2 font-semibold">useWindowResize 示例</div><div className="p-4 border rounded bg-gray-50 text-gray-800">當前窗口尺寸:<span className="font-mono">{size.width} x {size.height}</span></div></div>);
}
useDebouncedCallback —— 防抖回調
import useDebouncedCallback from "beautiful-react-hooks/useDebouncedCallback";
import { useState } from "react";export default function BeautifulHooks() {const [value, setValue] = useState("");const [debouncedValue, setDebouncedValue] = useState("");const debounced = useDebouncedCallback((val) => {setDebouncedValue(val);}, 800);const handleChange = (e) => {setValue(e.target.value);debounced(e.target.value);};return (<div className="container p-4"><div className="mb-2 font-semibold">useDebouncedCallback 示例</div><inputclassName="border px-2 py-1 rounded focus:outline-none focus:ring-2 focus:ring-blue-400 w-64"type="text"placeholder="輸入內容,800ms后觸發防抖"value={value}onChange={handleChange}/><div className="mt-2 text-gray-700 text-sm">最后一次防抖觸發內容:<span className="font-mono">{debouncedValue}</span></div></div>);
}
useThrottledCallback —— 節流回調
import useThrottledCallback from "beautiful-react-hooks/useThrottledCallback";
import { useState } from "react";export default function BeautifulHooks() {const [value, setValue] = useState("");const [throttledValue, setThrottledValue] = useState("");const throttled = useThrottledCallback((val) => {setThrottledValue(val);}, 800);const handleChange = (e) => {setValue(e.target.value);throttled(e.target.value);};return (<div className="container p-4"><div className="mb-2 font-semibold">useThrottledCallback 示例</div><inputclassName="border px-2 py-1 rounded focus:outline-none focus:ring-2 focus:ring-blue-400 w-64"type="text"placeholder="輸入內容,800ms節流觸發"value={value}onChange={handleChange}/><div className="mt-2 text-gray-700 text-sm">最后一次節流觸發內容:<span className="font-mono">{throttledValue}</span></div></div>);
}
useDidMount —— 組件掛載時執行
import useDidMount from "beautiful-react-hooks/useDidMount";
import { useState } from "react";export default function BeautifulHooks() {const [mounted, setMounted] = useState(false);useDidMount(() => {setMounted(true);});return (<div className="container p-4"><div className="mb-2 font-semibold">useDidMount 示例</div>{mounted && (<div className="p-4 border rounded bg-green-50 text-green-800">組件已掛載!</div>)}</div>);
}
useWillUnmount —— 組件卸載時執行
import useWillUnmount from "beautiful-react-hooks/useWillUnmount";
import { useState } from "react";export default function BeautifulHooks() {const [show, setShow] = useState(true);useWillUnmount(() => {alert("組件已卸載!");});return (<div className="container p-4"><div className="mb-2 font-semibold">useWillUnmount 示例</div><buttonclassName="px-4 py-2 rounded bg-blue-500 hover:bg-blue-600 text-white font-medium mb-4"onClick={() => setShow(false)}>卸載組件</button>{show && <UnmountDemo />}</div>);
}function UnmountDemo() {useWillUnmount(() => {alert("子組件已卸載!");});return (<div className="p-4 border rounded bg-green-50 text-green-800">子組件掛載中,點擊上方按鈕卸載</div>);
}
useLocalStorage —— 本地存儲狀態
import useLocalStorage from "beautiful-react-hooks/useLocalStorage";export default function BeautifulHooks() {const [count, setCount] = useLocalStorage("counter", 0);return (<div className="container p-4"><div className="mb-2 font-semibold">useLocalStorage 示例</div><div className="flex items-center gap-4 mb-4"><buttonclassName="px-4 py-2 rounded bg-blue-500 hover:bg-blue-600 text-white font-medium"onClick={() => setCount((c) => c - 1)}>-</button><span className="text-2xl font-mono">{count}</span><buttonclassName="px-4 py-2 rounded bg-blue-500 hover:bg-blue-600 text-white font-medium"onClick={() => setCount((c) => c + 1)}>+</button></div><div className="text-gray-500 text-sm">計數值會自動保存在 localStorage</div></div>);
}
useOnlineState —— 網絡狀態檢測
import useOnlineState from "beautiful-react-hooks/useOnlineState";export default function BeautifulHooks() {const online = useOnlineState();return (<div className="container p-4"><div className="mb-2 font-semibold">useOnlineState 示例</div><divclassName={`p-4 border rounded text-lg font-mono ${online? "bg-green-50 text-green-700 border-green-200": "bg-red-50 text-red-700 border-red-200"}`}>{online ? "當前在線" : "當前離線"}</div></div>);
}
useDarkMode —— 深色模式切換
import useDarkMode from "beautiful-react-hooks/useDarkMode";export default function BeautifulHooks() {const { toggle, enable, disable, isDarkMode } = useDarkMode();return (<divclassName={`container p-4 min-h-screen transition-colors duration-300 ${isDarkMode ? "bg-gray-900 text-white" : "bg-white text-gray-900"}`}><div className="mb-2 font-semibold">useDarkMode 示例</div><div className="flex gap-2 mb-4"><buttonclassName="px-4 py-2 rounded bg-blue-600 hover:bg-blue-700 text-white font-medium"onClick={enable}>啟用暗黑模式</button><buttonclassName="px-4 py-2 rounded bg-gray-300 hover:bg-gray-400 text-gray-900 font-medium"onClick={disable}>關閉暗黑模式</button><buttonclassName="px-4 py-2 rounded bg-indigo-500 hover:bg-indigo-600 text-white font-medium"onClick={toggle}>切換模式</button></div><div className="mb-2">點擊按鈕切換 isDarkMode 狀態</div><divclassName="p-4 border rounded bg-opacity-60"style={{ background: isDarkMode ? "#222" : "#f9fafb" }}>isDarkMode:{" "}<spanclassName={`inline-block px-2 py-1 rounded font-mono ${isDarkMode ? "bg-green-700 text-white" : "bg-gray-200 text-gray-900"}`}>{isDarkMode ? "true" : "false"}</span></div></div>);
}
常用 Hook 速查表
Hook 名稱 | 主要用途 |
---|---|
useToggle | 布爾/任意值切換 |
usePreviousValue | 獲取前一個值 |
useObjectState | 對象狀態管理 |
useValidatedState | 校驗型狀態 |
useEvent | 事件回調 |
useGlobalEvent | 全局事件監聽 |
useWindowResize | 監聽窗口尺寸變化 |
useDebouncedCallback | 防抖回調 |
useThrottledCallback | 節流回調 |
useDidMount | 組件掛載時執行 |
useWillUnmount | 組件卸載時執行 |
useLocalStorage | 本地存儲狀態 |
useOnlineState | 網絡狀態檢測 |
useDarkMode | 深色模式切換 |
總結
beautiful-react-hooks
?提供了豐富且實用的自定義 Hook,極大簡化了 React 組件的開發。建議結合官方文檔和 Playground 進行實踐體驗,快速掌握每個 Hook 的用法。
?beautiful-react-hooks庫——入門實踐常用hook詳解 - 高質量源碼分享平臺-免費下載各類網站源碼與模板及前沿動態資訊