」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > React Hooks 範例

React Hooks 範例

發佈於2024-11-08
瀏覽:640

React Hooks with Example

Introduction: Embracing the Power of React Hooks

Hey there, fellow UI developer! Are you ready to dive into the exciting world of React Hooks? If you've been working with React for a while, you might remember the days when class components were the go-to for managing state and side effects. But times have changed, and React Hooks have revolutionized the way we build components.

In this friendly guide, we'll explore 10 essential React Hooks, complete with example tutorials to help you understand and implement them in your projects. Whether you're new to Hooks or looking to deepen your knowledge, this post has got you covered. So, grab your favorite beverage, get comfortable, and let's embark on this React Hooks adventure together!

1. useState: Managing State with Ease

Let's kick things off with the most commonly used Hook: useState. This little gem allows you to add state to your functional components without the need for classes.

How it works

The useState Hook returns an array with two elements: the current state value and a function to update it. Here's a simple example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    

You clicked {count} times

); }

In this example, we're creating a counter that increases every time the button is clicked. The useState Hook initializes our count to 0, and we use the setCount function to update it.

When to use useState

  • When you need to manage local state in a functional component
  • For simple data types like numbers, strings, or booleans
  • When you want to avoid the complexity of class components for basic state management

2. useEffect: Handling Side Effects

Next up is useEffect, the Hook that lets you perform side effects in your components. It's like componentDidMount, componentDidUpdate, and componentWillUnmount all rolled into one!

How it works

useEffect takes two arguments: a function to run after render, and an optional array of dependencies. Here's an example:

import React, { useState, useEffect } from 'react';

function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);

    // Cleanup function
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // Empty dependency array means this effect runs once on mount

  return 
Window width: {width}px
; }

In this example, we're using useEffect to add an event listener for window resizing. The cleanup function removes the listener when the component unmounts.

When to use useEffect

  • For data fetching
  • Setting up subscriptions or event listeners
  • Manually changing the DOM
  • Logging or any other side effects that don't directly impact the render

3. useContext: Consuming Context with Ease

The useContext Hook provides a way to consume context in functional components without the need for render props or higher-order components.

How it works

First, you create a context using React.createContext(), then use the useContext Hook to consume it:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return ;
}

function App() {
  return (
    
      
    
  );
}

In this example, ThemedButton uses the useContext Hook to access the current theme value from ThemeContext.

When to use useContext

  • When you need to share data that can be considered "global" for a tree of React components
  • To avoid prop drilling (passing props through multiple levels of components)
  • For theming, user authentication, or any other application-wide data

4. useReducer: Managing Complex State Logic

When useState isn't enough, useReducer comes to the rescue. It's particularly useful for managing more complex state logic.

How it works

useReducer takes a reducer function and an initial state, and returns the current state paired with a dispatch method:

import React, { useReducer } from 'react';

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count   1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    
      Count: {state.count}
      
      
    >
  );
}

In this example, we're using useReducer to manage a counter with increment and decrement actions.

When to use useReducer

  • When you have complex state logic that involves multiple sub-values
  • When the next state depends on the previous one
  • When you want to optimize performance for components that trigger deep updates

5. useCallback: Optimizing Performance

The useCallback Hook can help you optimize the performance of your components by memoizing callback functions.

How it works

useCallback returns a memoized version of the callback that only changes if one of the dependencies has changed:

import React, { useState, useCallback } from 'react';

function ParentComponent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(c => c   1);
  }, []);

  return (
    

Count: {count}

); } function ChildComponent({ onIncrement }) { console.log('ChildComponent rendered'); return ; }

In this example, the increment function is memoized with useCallback, preventing unnecessary re-renders of ChildComponent.

When to use useCallback

  • When passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders
  • In combination with useMemo for creating memoized callbacks

6. useMemo: Memoizing Expensive Computations

Similar to useCallback, useMemo is used for optimization, but it memoizes the result of a computation.

How it works

useMemo takes a function and an array of dependencies, and only recomputes the memoized value when one of the dependencies has changed:

import React, { useState, useMemo } from 'react';

function ExpensiveComponent({ list }) {
  const [filter, setFilter] = useState('');

  const filteredList = useMemo(() => {
    console.log('Filtering list...');
    return list.filter(item => item.toLowerCase().includes(filter.toLowerCase()));
  }, [list, filter]);

  return (
    
setFilter(e.target.value)} placeholder="Filter list" />
    {filteredList.map(item => (
  • {item}
  • ))}
); }

In this example, we're using useMemo to memoize the filtered list, preventing unnecessary recalculations on every render.

When to use useMemo

  • For expensive calculations that don't need to be re-run on every render
  • When you want to avoid re-rendering child components unnecessarily
  • For referential equality checks in other Hooks' dependency arrays

7. useRef: Accessing DOM Elements and Storing Mutable Values

The useRef Hook provides a way to create a mutable reference that persists across re-renders.

How it works

useRef returns a mutable ref object whose .current property is initialized to the passed argument:

import React, { useRef, useEffect } from 'react';

function AutoFocusInput() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return ;
}

In this example, we're using useRef to get a reference to the input element and focus it when the component mounts.

When to use useRef

  • To access DOM elements directly
  • For storing mutable values that don't cause re-renders when updated
  • For keeping track of previous values in functional components

8. useImperativeHandle: Customizing Instance Value

useImperativeHandle customizes the instance value that is exposed to parent components when using ref.

How it works

useImperativeHandle should be used with forwardRef:

import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
    getValue: () => {
      return inputRef.current.value;
    }
  }));

  return ;
});

function Parent() {
  const fancyInputRef = useRef();

  const handleClick = () => {
    fancyInputRef.current.focus();
    console.log(fancyInputRef.current.getValue());
  };

  return (
    
); }

In this example, we're using useImperativeHandle to customize what instance value is exposed to the parent component.

When to use useImperativeHandle

  • When you want to customize the exposed instance value of a forwardRef component
  • To limit the exposed functionality of a child component to its parent

9. useLayoutEffect: Synchronous Effect Hook

useLayoutEffect is similar to useEffect, but it fires synchronously after all DOM mutations.

How it works

The signature is identical to useEffect, but it fires synchronously before the browser has a chance to paint:

import React, { useState, useLayoutEffect } from 'react';

function Tooltip() {
  const [tooltipHeight, setTooltipHeight] = useState(0);
  const tooltipRef = useRef();

  useLayoutEffect(() => {
    const height = tooltipRef.current.clientHeight;
    setTooltipHeight(height);
  }, []);

  return (
    
Tooltip content

The tooltip height is: {tooltipHeight}px

); }

In this example, we're using useLayoutEffect to measure the height of a DOM element synchronously before the browser paints.

When to use useLayoutEffect

  • When you need to make DOM measurements or mutations that should be applied synchronously before the browser paints
  • For animations that require measurements of DOM elements
  • When you want to avoid flickering caused by asynchronous updates

10. useDebugValue: Labeling Custom Hooks for DevTools

Last but not least, useDebugValue can be used to display a label for custom hooks in React DevTools.

How it works

useDebugValue accepts a value and an optional formatting function:

import React, { useState, useDebugValue } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  // ... Logic to determine if the friend is online ...

  useDebugValue(isOnline ? 'Online' : 'Offline');

  return isOnline;
}

function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);

  return (
    
  • {props.friend.name}
  • ); }

    In this example, we're using useDebugValue to display the friend's online status in React DevTools.

    When to use useDebugValue

    • In custom Hooks to provide more context about the Hook's state
    • For debugging complex custom Hooks
    • To improve the developer experience when working with custom Hooks

    Conclusion: Mastering React Hooks

    Wow, we've covered a lot of ground! From managing state with useState to optimizing performance with useMemo and useCallback, React Hooks offer a powerful and flexible way to build UI components. Let's recap the 10 Hooks we've explored:

    1. useState: For managing local state
    2. useEffect: For handling side effects
    3. useContext: For consuming context
    4. useReducer: For managing complex state logic
    5. useCallback: For optimizing performance of callbacks
    6. useMemo: For memoizing expensive computations
    7. useRef: For accessing DOM elements and storing mutable values
    8. useImperativeHandle: For customizing instance value
    9. useLayoutEffect: For synchronous effect execution
    10. useDebugValue: For labeling custom Hooks in DevTools

    Remember, the key to mastering React Hooks is practice. Start by incorporating them into your projects one at a time. As you become more comfortable, you'll find that Hooks can significantly simplify your code and make your components more reusable and easier to understand.

    Don't be afraid to experiment and combine different Hooks to solve complex problems. The React community is constantly coming up with new patterns and custom Hooks, so keep learning and sharing your discoveries!

    I hope this friendly guide has helped you get a better grasp on React Hooks. Happy coding, and may your components be forever functional and hook-tastic!

    "Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class." - React Documentation

    Now go forth and hook it up! ??

    版本聲明 本文轉載於:https://dev.to/nnnirajn/10-react-hooks-with-example-28kh?1如有侵犯,請聯絡[email protected]刪除
    最新教學 更多>
    • 對象擬合:IE和Edge中的封面失敗,如何修復?
      對象擬合:IE和Edge中的封面失敗,如何修復?
      To resolve this issue, we employ a clever CSS solution that solves the problem:position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%)...
      程式設計 發佈於2025-07-01
    • 如何使用不同數量列的聯合數據庫表?
      如何使用不同數量列的聯合數據庫表?
      合併列數不同的表 當嘗試合併列數不同的數據庫表時,可能會遇到挑戰。一種直接的方法是在列數較少的表中,為缺失的列追加空值。 例如,考慮兩個表,表 A 和表 B,其中表 A 的列數多於表 B。為了合併這些表,同時處理表 B 中缺失的列,請按照以下步驟操作: 確定表 B 中缺失的列,並將它們添加到表的...
      程式設計 發佈於2025-07-01
    • 找到最大計數時,如何解決mySQL中的“組函數\”錯誤的“無效使用”?
      找到最大計數時,如何解決mySQL中的“組函數\”錯誤的“無效使用”?
      如何在mySQL中使用mySql 檢索最大計數,您可能會遇到一個問題,您可能會在嘗試使用以下命令:理解錯誤正確找到由名稱列分組的值的最大計數,請使用以下修改後的查詢: 計數(*)為c 來自EMP1 按名稱組 c desc訂購 限制1 查詢說明 select語句提取名稱列和每個名稱...
      程式設計 發佈於2025-07-01
    • 如何將多種用戶類型(學生,老師和管理員)重定向到Firebase應用中的各自活動?
      如何將多種用戶類型(學生,老師和管理員)重定向到Firebase應用中的各自活動?
      Red: How to Redirect Multiple User Types to Respective ActivitiesUnderstanding the ProblemIn a Firebase-based voting app with three distinct user type...
      程式設計 發佈於2025-07-01
    • 如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
      如何將PANDAS DataFrame列轉換為DateTime格式並按日期過濾?
      將pandas dataframe列轉換為dateTime格式示例:使用column(mycol)包含以下格式的以下dataframe,以自定義格式:})指定的格式參數匹配給定的字符串格式。轉換後,MyCol列現在將包含DateTime對象。 date date filtering > = ...
      程式設計 發佈於2025-07-01
    • Java是否允許多種返回類型:仔細研究通用方法?
      Java是否允許多種返回類型:仔細研究通用方法?
      在Java中的多個返回類型:一種誤解類型:在Java編程中揭示,在Java編程中,Peculiar方法簽名可能會出現,可能會出現,使開發人員陷入困境,使開發人員陷入困境。 getResult(string s); ,其中foo是自定義類。該方法聲明似乎擁有兩種返回類型:列表和E。但這確實是如此嗎...
      程式設計 發佈於2025-07-01
    • 如何使用組在MySQL中旋轉數據?
      如何使用組在MySQL中旋轉數據?
      在關係數據庫中使用mySQL組使用mySQL組進行查詢結果,在關係數據庫中使用MySQL組,轉移數據的數據是指重新排列的行和列的重排以增強數據可視化。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的轉換為基於列。 Let's consider the following ...
      程式設計 發佈於2025-07-01
    • Go語言垃圾回收如何處理切片內存?
      Go語言垃圾回收如何處理切片內存?
      Garbage Collection in Go Slices: A Detailed AnalysisIn Go, a slice is a dynamic array that references an underlying array.使用切片時,了解垃圾收集行為至關重要,以避免潛在的內存洩...
      程式設計 發佈於2025-07-01
    • 為什麼PYTZ最初顯示出意外的時區偏移?
      為什麼PYTZ最初顯示出意外的時區偏移?
      與pytz 最初從pytz獲得特定的偏移。例如,亞洲/hong_kong最初顯示一個七個小時37分鐘的偏移: 差異源利用本地化將時區分配給日期,使用了適當的時區名稱和偏移量。但是,直接使用DateTime構造器分配時區不允許進行正確的調整。 example pytz.timezone(&#...
      程式設計 發佈於2025-07-01
    • 如何從PHP中的Unicode字符串中有效地產生對URL友好的sl。
      如何從PHP中的Unicode字符串中有效地產生對URL友好的sl。
      為有效的slug生成首先,該函數用指定的分隔符替換所有非字母或數字字符。此步驟可確保slug遵守URL慣例。隨後,它採用ICONV函數將文本簡化為us-ascii兼容格式,從而允許更廣泛的字符集合兼容性。 接下來,該函數使用正則表達式刪除了不需要的字符,例如特殊字符和空格。此步驟可確保slug僅包...
      程式設計 發佈於2025-07-01
    • 為什麼不使用CSS`content'屬性顯示圖像?
      為什麼不使用CSS`content'屬性顯示圖像?
      在Firefox extemers屬性為某些圖像很大,&& && && &&華倍華倍[華氏華倍華氏度]很少見,卻是某些瀏覽屬性很少,尤其是特定於Firefox的某些瀏覽器未能在使用內容屬性引用時未能顯示圖像的情況。這可以在提供的CSS類中看到:。 googlepic { 內容:url(&...
      程式設計 發佈於2025-07-01
    • 如何處理PHP文件系統功能中的UTF-8文件名?
      如何處理PHP文件系統功能中的UTF-8文件名?
      在PHP的Filesystem functions中處理UTF-8 FileNames 在使用PHP的MKDIR函數中含有UTF-8字符的文件很多flusf-8字符時,您可能會在Windows Explorer中遇到comploreer grounder grounder grounder gro...
      程式設計 發佈於2025-07-01
    • 如何干淨地刪除匿名JavaScript事件處理程序?
      如何干淨地刪除匿名JavaScript事件處理程序?
      刪除匿名事件偵聽器將匿名事件偵聽器添加到元素中會提供靈活性和簡單性,但是當需要刪除它們時,可以構成挑戰,而無需替換元素本身就可以替換一個問題。 element? element.addeventlistener(event,function(){/在這里工作/},false); 要解決此問題,請...
      程式設計 發佈於2025-07-01
    • 如何在Chrome中居中選擇框文本?
      如何在Chrome中居中選擇框文本?
      選擇框的文本對齊:局部chrome-inly-ly-ly-lyly solument 您可能希望將文本中心集中在選擇框中,以獲取優化的原因或提高可訪問性。但是,在CSS中的選擇元素中手動添加一個文本 - 對屬性可能無法正常工作。 初始嘗試 state)</option> < o...
      程式設計 發佈於2025-07-01
    • 如何解決AppEngine中“無法猜測文件類型,使用application/octet-stream...”錯誤?
      如何解決AppEngine中“無法猜測文件類型,使用application/octet-stream...”錯誤?
      appEngine靜態文件mime type override ,靜態文件處理程序有時可以覆蓋正確的mime類型,在錯誤消息中導致錯誤消息:“無法猜測mimeType for for file for file for [File]。 application/application/octet...
      程式設計 發佈於2025-07-01

    免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

    Copyright© 2022 湘ICP备2022001581号-3