最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How does this custom useAsync React hook maintain the latest function reference without triggering re-renders? - Stack

programmeradmin3浏览0评论
import { useEffect, useRef, useState } from 'react'

export function useAsync<T>(
  func: () => Promise<T> | undefined | null,
  deps = [],
) {
  const ref = useRef(func)
  ref.current = func
  const [value, setValue] = useState<T>()

  useEffect(() => {
    ref.current()?.then(setValue)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)

  return value
}

Please explain the principle of how this hook maintains the latest state of the function without causing re-rendering when it is used.

The hook maintains the latest function reference without causing unnecessary re-renders

import { useEffect, useRef, useState } from 'react'

export function useAsync<T>(
  func: () => Promise<T> | undefined | null,
  deps = [],
) {
  const ref = useRef(func)
  ref.current = func
  const [value, setValue] = useState<T>()

  useEffect(() => {
    ref.current()?.then(setValue)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)

  return value
}

Please explain the principle of how this hook maintains the latest state of the function without causing re-rendering when it is used.

The hook maintains the latest function reference without causing unnecessary re-renders

Share Improve this question edited Mar 18 at 15:34 Drew Reese 204k18 gold badges245 silver badges273 bronze badges asked Mar 18 at 8:57 user29986340user29986340 11 silver badge
Add a comment  | 

1 Answer 1

Reset to default 1

As long as the function is not part of deps, when it changes nothing that would trigger a re-render has occurred. The current field on the ref has been updated, but function is only called within the useEffect.

It is only when deps changes, that the effect is run, which, if the promise returned by calling the function succeeds, will set the state held in the hook.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论