Skip to main content

All hooks

useUpdateEffect

A hook that runs an effect only when dependencies change, skipping the initial mount. This is useful for responding to prop or state changes without running on first render.


The effect callback only fires on subsequent renders when dependencies change, not on the first render. Useful when you want to react to state changes but not the initial value.

Has the same API as useEffect — pass an effect function and a dependency array.

Usage

import { useUpdateEffect } from '@ts-hooks-kit/core'

function Example() {
  const result = useUpdateEffect()
  return <pre>{JSON.stringify(result, null, 2)}</pre>
}

API

function useUpdateEffect(effect: () => void | () => void, deps: unknown[]): void

A hook that runs an effect only when dependencies change, skipping the initial mount. This is useful for responding to prop or state changes without running on first render.

Parameters

NameTypeDefault valueDescription
effect`() => void() => void`-
depsunknown[]-The dependency array.

Returns

No return description available yet.

Hook

import { useEffect, useRef } from 'react'

/**
 * A hook that runs an effect only when dependencies change, skipping the initial mount.
 * This is useful for responding to prop or state changes without running on first render.
 *
 * @param {() => void | (() => void)} effect - The effect function to run.
 * @param {unknown[]} deps - The dependency array.
 *
 * @example
 * ```tsx
 * function Component({ value }) {
 *   useUpdateEffect(() => {
 *     console.log('Value changed:', value);
 *   }, [value]);
 *
 *   return <div>{value}</div>;
 * }
 * ```
 */
export function useUpdateEffect(
  effect: () => void | (() => void),
  deps: unknown[],
): void {
  const isFirstMount = useRef(true)

  useEffect(() => {
    if (isFirstMount.current) {
      isFirstMount.current = false
      return
    }

    return effect()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps)
}