useUpdateEffect
A hook to run an effect only when the component updates
Installation
npx shadcn@latest add @hooks/use-update-effectpnpm dlx shadcn@latest add @hooks/use-update-effectyarn dlx shadcn@latest add @hooks/use-update-effectbun x shadcn@latest add @hooks/use-update-effectCopy and paste the following code into your project.
import { useEffect } from 'react'
import { useLatest } from '@/registry/hooks/use-latest'
export function useUnmount(fn: () => void) {
const fnRef = useLatest(fn)
useEffect(
() => () => {
fnRef.current()
},
[],
)
}import { useEffect, useRef } from 'react'
import { useUnmount } from '@/registry/hooks/use-unmount'
import type { DependencyList, EffectCallback } from 'react'
export function useUpdateEffect(effect: EffectCallback, deps: DependencyList) {
const mounted = useRef(false)
// for react-refresh
useUnmount(() => {
mounted.current = false
})
useEffect(() => {
if (!mounted.current) {
mounted.current = true
return
}
return effect()
}, deps)
}API
/**
* A hook to run an effect only when the component updates
* @param effect - The effect to run
* @param deps - The dependencies to run the effect on
*/
export function useUpdateEffect(
effect: EffectCallback,
deps: DependencyList,
): voidCredits
Last updated on