React hooks 是特殊的函數,可讓您在功能元件中使用 React 功能,例如狀態和生命週期方法。它們是在 React 16.8 中引入的,目的是簡化元件模型,並使跨元件共享狀態邏輯變得更容易。
狀態管理: 像 useState 這樣的鉤子允許您在功能元件中新增和管理狀態,而不需要將它們轉換為類別元件。
副作用: useEffect 鉤子可讓您執行副作用,例如資料擷取、訂閱或手動變更 DOM,類似於類別元件中的生命週期方法。
可重複使用性:自訂掛鉤可讓您跨不同元件封裝和重複使用有狀態邏輯。
更簡潔的程式碼: 掛鉤有助於保持組件
1 useState
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
2 useEffect
import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
3 useContext
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div className={`theme-${theme}`}>Current theme: {theme}</div>; };
4 使用Reducer
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); };
5 useMemo
import React, { useMemo, useState } from 'react'; const ExpensiveComputation = ({ number }) => { const compute = (num) => { return num * 1000; // Simulate an expensive computation }; const result = useMemo(() => compute(number), [number]); return <div>Computed Result: {result}</div>; };
6 useCallback
import React, { useCallback, useState } from 'react'; const Button = React.memo(({ onClick, children }) => { console.log('Button rendered'); return <button onClick={onClick}>{children}</button>; }); const App = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), []); return ( <div> <p>Count: {count}</p> <Button onClick={increment}>Increment</Button> </div> ); };
7 useRef
import React, { useRef } from 'react'; const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); };
8 useLayoutEffect
import React, { useLayoutEffect, useRef } from 'react'; const LayoutEffectExample = () => { const divRef = useRef(); useLayoutEffect(() => { console.log('Height:', divRef.current.clientHeight); }, []); return <div ref={divRef}>This is a div</div>; };
9 使用ImperativeHandle
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
10 useDebugValue
- 描述: 在 React DevTools 中顯示自訂掛鉤的標籤,以便於偵錯。
- 範例:
import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
11 useFetch
- 描述: 用於從 API 取得資料的自訂掛鉤。
- 範例:
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div className={`theme-${theme}`}>Current theme: {theme}</div>; };
12 使用本地儲存
- 描述: 將狀態與本地儲存同步以跨會話保存資料。
- 範例:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); };
13 用上一個
- 描述:傳回狀態或道具的先前值。
- 範例:
import React, { useMemo, useState } from 'react'; const ExpensiveComputation = ({ number }) => { const compute = (num) => { return num * 1000; // Simulate an expensive computation }; const result = useMemo(() => compute(number), [number]); return <div>Computed Result: {result}</div>; };
14 使用Debounce
- 描述:對值或函數呼叫進行反跳,延遲執行直到指定的延遲之後。
- 範例:
import React, { useCallback, useState } from 'react'; const Button = React.memo(({ onClick, children }) => { console.log('Button rendered'); return <button onClick={onClick}>{children}</button>; }); const App = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), []); return ( <div> <p>Count: {count}</p> <Button onClick={increment}>Increment</Button> </div> ); };
15 useOnClickOutside
- 說明: 偵測指定元素外部的點擊,對於關閉彈出視窗或下拉式選單很有用。
- 範例:
import React, { useRef } from 'react'; const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); };
16 使用間隔
- 說明: 設定一個時間間隔,以指定的時間間隔重複執行某個函數。
- 範例:
import React, { useLayoutEffect, useRef } from 'react'; const LayoutEffectExample = () => { const divRef = useRef(); useLayoutEffect(() => { console.log('Height:', divRef.current.clientHeight); }, []); return <div ref={divRef}>This is a div</div>; };
17 useTimeout
- 描述: 設定逾時以在指定的延遲後執行函數。
- 範例:
import React, { useImperativeHandle, forwardRef, useRef } from 'react'; const CustomInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} type="text" />; }); const Parent = () => { const ref = useRef(); return ( <div> <CustomInput ref={ref} /> <button onClick={() => ref.current.focus()}>Focus Input</button> </div> ); };
18 useMediaQuery
- 描述: 檢查媒體查詢是否匹配,從而實現響應式設計邏輯。
- 範例:
import { useDebugValue } from 'react'; const useCustomHook = (value) => { useDebugValue(value ? 'Value is true' : 'Value is false'); return value; }; const DebugExample = () => { const isTrue = useCustomHook(true); return <div>Check the React DevTools</div>; };
19 使用ScrollPosition
- 描述:追蹤視窗的目前捲動位置。
- 範例:
import { useState, useEffect } from 'react'; const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchData = async () => { const response = await fetch(url); const result = await response.json(); setData(result); setLoading(false); }; fetchData(); }, [url]); return { data, loading }; };
20 使用按鍵
- 描述:偵測是否按下特定鍵。
- 範例:
import { useState, useEffect } from 'react'; const useLocalStorage = (key, initialValue) => { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(storedValue)); } catch (error) { console.error(error); } }, [key, storedValue]); return [storedValue, setStoredValue]; };
此清單現在包含每個鉤子的描述,讓您更清楚地了解其用途和用例。如果您需要更多詳細資訊或範例,請隨時詢問!
以上是提升你的 React 技能:理解並使用 Hooks的詳細內容。更多資訊請關注PHP中文網其他相關文章!