StateBeginnerFully SSR-safehooks/state/usePreviousDistinct.ts

usePreviousDistinct

Previous value only when the current value actually changed.

Import

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

API

Signature

usePreviousDistinct<T>(value, compare?) → T | undefined

When to use

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

SSR / Next.js

Fully SSR-safe. Pure React state.

Live playground

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

Live playgroundEdit · run with real @/hooks · usePreviousDistinct
Editor
function DistinctPrev() {
  const [user, setUser] = useState({ id: 1, name: 'Ada' });
  const prev = usePreviousDistinct(user, (a, b) => a.id === b.id);

  return (
    <button onClick={() => setUser({ id: 2, name: 'Grace' })}>
      prev id: {prev?.id ?? 'none'}
    </button>
  );
}
Preview

Implementation source

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

hooks/state/usePreviousDistinct.ts
import { useRef } from 'react';

export type EqualityFn<T> = (a: T, b: T) => boolean;

/**
 * Previous value that only updates when the value is distinct
 * according to the equality function (default: Object.is).
 */
export function usePreviousDistinct<T>(
  value: T,
  compare: EqualityFn<T> = Object.is,
): T | undefined {
  const prevRef = useRef<T | undefined>(undefined);
  const curRef = useRef(value);
  const isFirst = useRef(true);

  if (isFirst.current) {
    isFirst.current = false;
  } else if (!compare(curRef.current, value)) {
    prevRef.current = curRef.current;
    curRef.current = value;
  }

  return prevRef.current;
}

Copy-paste example

usePreviousDistinct.example.tsx
'use client';

import { useState } from 'react';
import { usePreviousDistinct } from '@/hooks';

export function DistinctPrev() {
  const [user, setUser] = useState({ id: 1, name: 'Ada' });
  const prev = usePreviousDistinct(user, (a, b) => a.id === b.id);

  return (
    <button onClick={() => setUser({ id: 2, name: 'Grace' })}>
      prev id: {prev?.id ?? 'none'}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Keep state setters stable; prefer action helpers over manual setState spreads.
  • Source of truth: open hooks/state/usePreviousDistinct.ts for implementation details