StateBeginnerFully SSR-safehooks/state/usePrevious.ts

usePrevious

Read the value from the previous render.

Import

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

API

Signature

usePrevious<T>(value) → T | undefined

When to use

Use usePrevious 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 · usePrevious
Editor
function Diff() {
  const [value, setValue] = useState(0);
  const prev = usePrevious(value);

  return (
    <div>
      <p>Now: {value} · Before: {prev ?? '—'}</p>
      <button onClick={() => setValue((v) => v + 1)}>Inc</button>
    </div>
  );
}
Preview

Implementation source

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

hooks/state/usePrevious.ts
import { useEffect, useRef } from 'react';

/** Returns the previous render's value (undefined on first render). */
export function usePrevious<T>(value: T): T | undefined {
  const ref = useRef<T | undefined>(undefined);

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current;
}

Copy-paste example

usePrevious.example.tsx
'use client';

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

export function Diff() {
  const [value, setValue] = useState(0);
  const prev = usePrevious(value);

  return (
    <div>
      <p>Now: {value} · Before: {prev ?? '—'}</p>
      <button onClick={() => setValue((v) => v + 1)}>Inc</button>
    </div>
  );
}

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/usePrevious.ts for implementation details