admin管理员组文章数量:1387434
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 badge1 Answer
Reset to default 1As 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.
本文标签:
版权声明:本文标题:reactjs - How does this custom useAsync React hook maintain the latest function reference without triggering re-renders? - Stack 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744515149a2610118.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论