PerformanceIntermediateSSR-safehooks/performance/useWhyDidYouUpdate.ts

useWhyDidYouUpdate

Log which props changed (debug).

Import

TypeScript
import { useWhyDidYouUpdate } from '@/hooks';

API

Signature

useWhyDidYouUpdate(name, props, enabled?)

When to use

Use useWhyDidYouUpdate instead of re-implementing the same pattern in multiple components.

SSR / Next.js

SSR-safe. Timers and rAF only run after mount / interactions.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useWhyDidYouUpdate
Editor
function Card(props: { title: string; open: boolean }) {
  useWhyDidYouUpdate('Card', props);
  return <div>{props.title}</div>;
}
Preview

Implementation source

Full library source for useWhyDidYouUpdate — copy into your project when you are not installing a package yet.

hooks/performance/useWhyDidYouUpdate.ts
import { useEffect, useRef } from 'react';

/**
 * Logs which props changed between renders (debug utility).
 * No-ops in production builds when `enabled` is false.
 */
export function useWhyDidYouUpdate(
  name: string,
  props: Record<string, unknown>,
  enabled = process.env.NODE_ENV !== 'production',
): void {
  const prev = useRef(props);

  useEffect(() => {
    if (!enabled) {
      prev.current = props;
      return;
    }

    const allKeys = new Set([
      ...Object.keys(prev.current),
      ...Object.keys(props),
    ]);
    const changes: Record<string, { from: unknown; to: unknown }> = {};

    allKeys.forEach((key) => {
      if (!Object.is(prev.current[key], props[key])) {
        changes[key] = { from: prev.current[key], to: props[key] };
      }
    });

    if (Object.keys(changes).length > 0) {
      // eslint-disable-next-line no-console
      console.log('[why-did-you-update]', name, changes);
    }

    prev.current = props;
  });
}

Copy-paste example

useWhyDidYouUpdate.example.tsx
'use client';

import { useWhyDidYouUpdate } from '@/hooks';

export function Card(props: { title: string; open: boolean }) {
  useWhyDidYouUpdate('Card', props);
  return <div>{props.title}</div>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Stable callbacks prevent child re-renders. Always cancel debounce on unmount (handled for you).
  • Source of truth: open hooks/performance/useWhyDidYouUpdate.ts for implementation details