实现useLatest

1,335 阅读1分钟

自定义hooks

作为react的使用者,自定义hooks是常见的业务需求,小弟技术水平有限,只能先借花献佛聊下公司里大佬们封装的自定义hooks了

import { useRef } from 'react';

/**
 * 返回当前最新值的 Hook
 * @param value
 * @returns
 */
export function useLatest<T>(value: T) {
  const ref = useRef(value);
  ref.current = value;

  return ref;
}

useLatest 会保留每次运行过程中最新的值,是很多hooks的基础。

用法如下

import React, { useState, useEffect } from 'react';
import { useLatest } from '@pansy/react-hooks';


export default () => {
  const [count, setCount] = useState(0);


  const latestCountRef = useLatest(count);


  useEffect(() => {
    const interval = setInterval(() => {
      setCount(latestCountRef.current + 1);
    }, 1000);


    return () => clearInterval(interval);
  }, []);


   return (
     <p>count: {count}</p>
   );
 };

个人的分享记录,不喜勿喷。