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.