Skip to content

usePrevious

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

usePrevious

Access the previous render's value of a state or prop variable. This is highly useful when you need to execute side effects comparing how a value changed over time.

Usage Examples

Basic

Comparing the current state with the state from the immediately preceding render cycle.

import { useState } from "react";
import { usePrevious } from "react-hook-lab";

function CounterLog() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  return (
    <div>
      <p>Current Count: {count}</p>
      {/* On the very first render, prevCount will be undefined */}
      <p>Previous Count: {prevCount !== undefined ? prevCount : "None"}</p>
      
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Common

Using a strict default fallback for the initial render so the hook never returns undefined.

import { useState, useEffect } from "react";
import { usePrevious } from "react-hook-lab";

function SearchTracker() {
  const [query, setQuery] = useState("");
  // We pass "" as the second argument, ensuring the return type is purely string
  const prevQuery = usePrevious(query, "");

  useEffect(() => {
    if (prevQuery !== query) {
      console.log(`User changed search from "${prevQuery}" to "${query}"`);
    }
  }, [query, prevQuery]);

  return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}

Advanced

Detecting deep property changes on complex objects or props without firing deep equality checks manually.

import { usePrevious } from "react-hook-lab";

function ProfileEditor({ user }: { user: { id: string; role: string } }) {
  const prevUser = usePrevious(user);

  if (prevUser && prevUser.role !== user.role) {
    console.log(`Role escalated from ${prevUser.role} to ${user.role}!`);
  }

  return <div>Editing {user.id}</div>;
}

API Reference

Parameters

  • value
    • Type: T
    • Description: The state, prop, or derived value to track across renders.
  • defaultValue (Optional)
    • Type: T
    • Description: An optional default value returned strictly on the first component render before a previous value exists.

Return Type

Returns the previous value of type T. If no defaultValue is provided, it returns T | undefined for the very first render.

Core Working

The hook utilizes a combination of React's useRef and useEffect. Because useEffect always executes after the component has painted and rendered, the useRef retains the old value during the current render phase. Once the render finishes, the useEffect fires and updates the internal useRef to hold the new value. This clever misalignment in timing ensures that whenever the component renders, the ref still holds the data from the immediately preceding cycle.

Clone this wiki locally