Shadcn Hooks

useDeepCompareLayoutEffect

A hook to use a deep compare layout effect

useDeepCompareLayoutEffect

npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-deep-compare-layout-effect.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-deep-compare-layout-effect.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-deep-compare-layout-effect.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-deep-compare-layout-effect.json"

Copy and paste the following code into your project.

use-deep-compare-layout-effect.ts
import { dequal } from 'dequal'
import { useLayoutEffect, useRef } from 'react'
import type { DependencyList, EffectCallback } from 'react'

export function useDeepCompareLayoutEffect(
  effect: EffectCallback,
  deps: DependencyList,
) {
  const ref = useRef<DependencyList>(deps)

  if (!ref.current || !dequal(ref.current, deps)) {
    ref.current = deps
  }

  useLayoutEffect(effect, ref.current)
}

credits

Last updated on