当前位置:   article > 正文

React Hooks 全解: 常用 Hooks 及使用场景详解

React Hooks 全解: 常用 Hooks 及使用场景详解

React Hooks 是 React 16.8 版本引入的一项重要特性,它极大地简化和优化了函数组件的开发过程。 React 中常用的 10 个 Hooks,包括 useState、useEffect、useContext、useReducer、useCallback、useMemo、useRef、useLayoutEffect、useImperativeHandle 和 useDebugValue。这些 Hooks 涵盖了状态管理、副作用处理、性能优化、DOM 操作等各个方面,为开发者提供了强大的工具,大幅提高了开发效率和代码质量。

在这里插入图片描述

无论您是 React 新手还是老手,全面而深入的 Hooks 知识,帮助您更好地掌握 React 函数组件的开发技巧。让我们一起探索 React Hooks 的强大功能,提升您的 React 开发水平。

  1. useState

    • 使用场景: 管理组件内部的状态
    • 示例代码:
      import { useState } from 'react';
      
      function Counter() {
        const [count, setCount] = useState(0);
      
        return (
          <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Click me</button>
          </div>
        );
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
  2. useEffect

    • 使用场景: 处理组件生命周期,例如数据获取、订阅、手动更改 DOM 等
    • 示例代码:
      import { useState, useEffect } from 'react';
      
      function FetchData() {
        const [data, setData] = useState([]);
      
        useEffect(() => {
          async function fetchData() {
            const response = await fetch('/api/data');
            const data = await response.json();
            setData(data);
          }
          fetchData();
        }, []);
      
        return (
          <div>
            <h1>Fetched Data</h1>
            <ul>
              {data.map((item) => (
                <li key={item.id}>{item.name}</li>
              ))}
            </ul>
          </div>
        );
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
  3. useContext

    • 使用场景: 跨组件传递数据,避免"prop drilling"
    • 示例代码:
      import { createContext, useContext } from 'react';
      
      const ThemeContext = createContext('light');
      
      function App() {
        return (
          <ThemeContext.Provider value="dark">
            <ThemedButton />
          </ThemeContext.Provider>
        );
      }
      
      function ThemedButton() {
        const theme = useContext(ThemeContext);
        return <button style={{ backgroundColor: theme === 'dark' ? 'black' : 'white' }}>Theme Button</button>;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
  4. useReducer

    • 使用场景: 管理复杂的状态逻辑
    • 示例代码:
      import { useReducer } from 'react';
      
      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, { count: 0 });
      
        return (
          <div>
            <p>Count: {state.count}</p>
            <button onClick={() => dispatch({ type: 'increment' })}>+</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
          </div>
        );
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
  5. useCallback

    • 使用场景: 缓存函数引用,优化性能
    • 示例代码:
      import { useState, useCallback } from 'react';
      
      function Parent() {
        const [count, setCount] = useState(0);
      
        const handleClick = useCallback(() => {
          setCount(count + 1);
        }, [count]);
      
        return (
          <div>
            <p>Count: {count}</p>
            <ChildComponent onClick={handleClick} />
          </div>
        );
      }
      
      function ChildComponent({ onClick }) {
        console.log('ChildComponent rendered');
        return <button onClick={onClick}>Increment</button>;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
  6. useMemo

    • 使用场景: 缓存计算结果,优化性能
    • 示例代码:
      import { useState, useMemo } from 'react';
      
      function ExpensiveCalculation() {
        const [number, setNumber] = useState(0);
      
        const doubledNumber = useMemo(() => {
          return slowlyDoubleNumber(number);
        }, [number]);
      
        return (
          <div>
            <input type="number" value={number} onChange={(e) => setNumber(parseInt(e.target.value))} />
            <p>Doubled number: {doubledNumber}</p>
          </div>
        );
      }
      
      function slowlyDoubleNumber(n) {
        // 模拟一个耗时的计算
        let i = 0;
        while (i < 1000000000) i++;
        return n * 2;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
  7. useRef

    • 使用场景: 获取 DOM 元素引用,保存可变状态
    • 示例代码:
      import { useRef } from 'react';
      
      function FocusInput() {
        const inputRef = useRef(null);
      
        const handleClick = () => {
          inputRef.current.focus();
        };
      
        return (
          <div>
            <input type="text" ref={inputRef} />
            <button onClick={handleClick}>Focus Input</button>
          </div>
        );
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
  8. useLayoutEffect

    • 使用场景: 处理 DOM 操作,需要同步执行
    • 示例代码:
      import { useLayoutEffect, useRef } from 'react';
      
      function MeasureElement() {
        const elementRef = useRef(null);
      
        useLayoutEffect(() => {
          const element = elementRef.current;
          console.log('Element width:', element.offsetWidth);
        }, []);
      
        return <div ref={elementRef}>This is the element to measure</div>;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
  9. useImperativeHandle

    • 使用场景: 暴露组件实例方法给父组件
    • 示例代码:
      import { forwardRef, useImperativeHandle, useRef } from 'react';
      
      const CustomInput = forwardRef((props, ref) => {
        const inputRef = useRef(null);
      
        useImperativeHandle(ref, () => ({
          focus: () => {
            inputRef.current.focus();
          }
        }));
      
        return <input type="text" ref={inputRef} />;
      });
      
      function App() {
        const inputRef = useRef(null);
      
        const handleClick = () => {
          inputRef.current.focus();
        };
      
        return (
          <div>
            <CustomInput ref={inputRef} />
            <button onClick={handleClick}>Focus Input</button>
          </div>
        );
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
  10. useDebugValue

    • 使用场景: 为自定义 Hooks 提供调试标签
    • 示例代码:
      import { useState, useDebugValue } from 'react';
      
      function useCustomHook() {
        const [state, setState] = useState(0);
        useDebugValue(`Current state: ${state}`);
        // 自定义 Hook 的其他逻辑
        return [state, setState];
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8

这些是 React 中一些其他常用的 Hooks,它们可以帮助你进一步优化组件的逻辑和性能。每个 Hook 都有其特定的使用场景和使用方式,希望这个列表能为你提供一些参考和启发。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/442300
推荐阅读
相关标签
  

闽ICP备14008679号