常用的 React Hooks 的介绍和示例

目录

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

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

1. useState

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

javascript 复制代码
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。

javascript 复制代码
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。

javascript 复制代码
import React, { useContext } from 'react';

const MyContext = React.createContext(null);

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

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

4. useReducer

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

javascript 复制代码
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,以避免不必要的重新渲染。

javascript 复制代码
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,以避免不必要的计算。

javascript 复制代码
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。

javascript 复制代码
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。

javascript 复制代码
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 变更之后同步调用,而不是异步调用。

javascript 复制代码
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。

javascript 复制代码
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>
  );
}
相关推荐
前端君1 天前
实现最大异步并发执行队列
javascript
Nan_Shu_6141 天前
Web前端面试题(2)
前端
知识分享小能手1 天前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队1 天前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光1 天前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军1 天前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite
huangql5201 天前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
Qlittleboy1 天前
uniapp如何使用本身的字体图标
javascript·vue.js·uni-app
Days20501 天前
LeaferJS好用的 Canvas 引擎
前端·开源
小白菜学前端1 天前
vue2 常用内置指令总结
前端·vue.js