# 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。
相关推荐
excel8 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel9 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼10 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping10 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙11 小时前
[译] Composition in CSS
前端·css
白水清风11 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix12 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780012 小时前
new、原型和原型链浅析
前端·javascript
阿星做前端12 小时前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧12 小时前
Promise 的使用
前端·javascript