Shadcn Hooks

useUpdateEffect

A hook to run an effect only when the component updates

Installation

npx shadcn@latest add @hooks/use-update-effect
pnpm dlx shadcn@latest add @hooks/use-update-effect
yarn dlx shadcn@latest add @hooks/use-update-effect
bun x shadcn@latest add @hooks/use-update-effect

Copy and paste the following code into your project.

use-unmount.ts
import { useEffect } from 'react'
import { useLatest } from '@/registry/hooks/use-latest'

export function useUnmount(fn: () => void) {
  const fnRef = useLatest(fn)

  useEffect(
    () => () => {
      fnRef.current()
    },
    [],
  )
}

use-update-effect.ts
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,
): void

Credits

Last updated on