当前位置: 首页 > article >正文

常用的 React Hooks 的介绍和示例

目录

  • 1. useState
  • 2. useEffect
  • 3. useContext
  • 4. useReducer
  • 5. useCallback
  • 6. useMemo
  • 7. useRef
  • 8. useImperativeHandle
  • 9. useLayoutEffect
  • 10. useDebugValue

常用的 React Hooks 的介绍和示例:

1. useState

useState 是一个用于在函数组件中添加状态的 Hook。

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0); // 初始化状态

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

2. useEffect

useEffect 是一个用于在函数组件中执行副作用(如数据获取、订阅或手动更改 DOM)的 Hook。

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

3. useContext

useContext 是一个用于在函数组件中访问 React Context 的 Hook。

import React, { useContext } from 'react';

const MyContext = React.createContext(null);

function Example() {
  const value = useContext(MyContext);

  return <div>{value}</div>;
}

4. useReducer

useReducer 是一个用于在函数组件中使用更复杂的状态逻辑的 Hook。

import React, { 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 Example() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>
        Increment
      </button>
      <button onClick={() => dispatch({ type: 'decrement' })}>
        Decrement
      </button>
    </div>
  );
}

5. useCallback

useCallback 是一个用于缓存函数的 Hook,以避免不必要的重新渲染。

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

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

  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

6. useMemo

useMemo 是一个用于缓存计算值的 Hook,以避免不必要的计算。

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

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

  const memoizedValue = useMemo(() => {
    return count * 2;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Memoized Value: {memoizedValue}</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

7. useRef

useRef 是一个用于在函数组件中访问 DOM 元素或存储可变值的 Hook。

import React, { useRef } from 'react';

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

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

8. useImperativeHandle

useImperativeHandle 是一个用于自定义暴露给父组件的实例值的 Hook。

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

function FancyInput(props, ref) {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} />;
}

FancyInput = React.forwardRef(FancyInput);

function ParentComponent() {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <FancyInput ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

9. useLayoutEffect

useLayoutEffect 是一个与 useEffect 类似的 Hook,但它会在所有 DOM 变更之后同步调用,而不是异步调用。

import React, { useLayoutEffect } from 'react';

function Example() {
  useLayoutEffect(() => {
    console.log('This runs synchronously after all DOM changes');
  });

  return <div>Example</div>;
}

10. useDebugValue

useDebugValue 是一个用于在 React DevTools 中显示自定义 Hook 的调试值的 Hook。

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

function useCustomHook(initialValue) {
  const [value, setValue] = useState(initialValue);

  useDebugValue(`Current value: ${value}`);

  return [value, setValue];
}

function Example() {
  const [count, setCount] = useCustomHook(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

http://www.kler.cn/a/553804.html

相关文章:

  • springboot-ffmpeg-m3u8-convertor nplayer视频播放弹幕 artplayer视频弹幕
  • GITHUB的若干操作
  • 【LeetCode Hot100 链表(上)】相交链表、反转链表、回文链表、环形链表、合并两个有序链表、两数相加
  • 学习总结2.19
  • Flutter基础入门
  • HarmonyOS全栈开发指南:从入门到精通,构建万物智联的未来生态(三)
  • INA219电流、电压、功率测量芯片应用
  • 使用(xshell+xftp)将前端项目部署到服务器
  • LeetCode 0624.数组列表中的最大距离:只关心最小最大值
  • 智慧场馆运营系统
  • jenkins自动发版vue前端笔记
  • 2021年下半年软件设计师下午试卷题型和考点总结(附真题及答案解析)
  • JavaScript数组-遍历数组
  • 手机控制电脑远程关机
  • sklearn.ConfusionMatrixDisplay可视化混淆矩阵
  • Golang GORM系列:GORM无缝集成web框架
  • Vue.js 定义 Vue CLI 配置
  • C# ConcurrentQueue 使用详解
  • Python数据可视化简介
  • 支持 30+ AI 大模型!一站式聚合 GPT-4、Claude、DeepSeek、通义千问、文心一言等全球顶级模型!