# 14 React 自定义Hook详解

自定义 Hook 是一个函数,其名称以 "use" 开头,函数内部可以调用其他 Hook。自定义 Hook 是一个函数,其名称以 "use" 开头,函数内部可以调用其他 Hook。下面是几个自定义 Hook 的例子以及需要注意的知识:

1. 使用状态管理数据

javascript 复制代码
import { useState } from 'react';

function useCounter(initialValue, step) {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount(count + step);
  const decrement = () => setCount(count - step);

  return { count, increment, decrement };
}

// 在组件中使用
function Counter() {
  const { count, increment, decrement } = useCounter(0, 1);

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

注意:

  • 自定义 Hook 可以帮助复用状态逻辑。
  • 在使用状态时,确保传递正确的默认值和参数。

2. 使用生命周期

javascript 复制代码
import { useState, useEffect } from 'react';

function useDocumentTitle(title) {
  useEffect(() => {
    document.title = title;

    return () => {
      document.title = 'React App'; // 在卸载时重置标题
    };
  }, [title]);
}

// 在组件中使用
function TitleUpdater() {
  useDocumentTitle('New Title');

  return <div>Updating Document Title</div>;
}

注意:

  • useEffect 用于处理副作用,如修改文档标题。
  • 注意 useEffect 的第二个参数,这决定了何时应该重新执行副作用。

3. 订阅和取消订阅事件

javascript 复制代码
import { useEffect } from 'react';

function useEventListener(eventName, handler) {
  useEffect(() => {
    const eventListener = (event) => handler(event);
    window.addEventListener(eventName, eventListener);

    return () => {
      window.removeEventListener(eventName, eventListener);
    };
  }, [eventName, handler]);
}

// 在组件中使用
function EventListenerComponent() {
  const handleScroll = (event) => {
    console.log('Scrolled:', event);
  };

  useEventListener('scroll', handleScroll);

  return <div>Listening to Scroll Events</div>;
}

注意:

  • useEffect 在这里用于添加和移除事件监听器。
  • 注意清除函数,以免内存泄漏。

4. 处理本地存储

javascript 复制代码
import { useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) : initialValue;
  });

  const updateValue = (newValue) => {
    setValue(newValue);
    localStorage.setItem(key, JSON.stringify(newValue));
  };

  return [value, updateValue];
}

// 在组件中使用
function LocalStorageComponent() {
  const [name, setName] = useLocalStorage('name', '');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  return (
    <div>
      <input type="text" value={name} onChange={handleChange} />
      <p>Hello, {name}!</p>
    </div>
  );
}

注意:

  • 使用 useState 和 useEffect 来管理本地存储。
  • 注意对存储数据进行序列化和反序列化。

注意事项:

  • 自定义 Hook 本质上是函数,但需要符合特定的命名规范以及 Hook 规则。
  • 在自定义 Hook 内部,可以使用其他 Hook,但不要在普通 JavaScript 函数中调用 Hook。
相关推荐
Z兽兽5 小时前
React@18+Vite项目配置env文件
前端·react.js·前端框架
SuniaWang5 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
A_nanda6 小时前
根据AI提示排查vue前端项目
前端·javascript·vue.js
happymaker06266 小时前
web前端学习日记——DAY05(定位、浮动、视频音频播放)
前端·学习·音视频
~无忧花开~6 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架
LegendNoTitle7 小时前
计算机三级等级考试 网络技术 选择题考点详细梳理
服务器·前端·经验分享·笔记·php
@大迁世界7 小时前
1.什么是 ReactJS?
前端·javascript·react.js·前端框架·ecmascript
BJ-Giser8 小时前
Cesium 基于EZ-Tree的植被效果
前端·可视化·cesium
王码码20359 小时前
Flutter for OpenHarmony:Flutter 三方库 algoliasearch 毫秒级云端搜索体验(云原生搜索引擎)
android·前端·git·flutter·搜索引擎·云原生·harmonyos
发现一只大呆瓜9 小时前
深入浅出 AST:解密 Vite、Babel编译的底层“黑盒”
前端·面试·vite