Typed HooksGetting StartedusePrevious

usePrevious

A custom hook for accessing the previous value of a state or prop in React.

usePrevious is a simple yet powerful custom React hook that allows you to access the previous value of a prop or state in your functional components. This is especially useful when you need to compare current and previous values to trigger side effects or conditionally render components based on value changes.

Unlike class components where you could access previous props or state in the componentDidUpdate lifecycle method, functional components don't have built-in access to previous values. This hook leverages React's useRef and useEffect to provide this functionality in a clean, reusable way.

0
Previous: N/A

API

usePrevious <T>(value: T): T | undefined

Parameters

ParameterTypeDescription
valueTThe current value to track.

Returns

  • Returns (T | undefined): The previous value of the tracked state or prop. Returns undefined on the first render.

Hook

import { useEffect, useRef } from 'react'
 
/**
 * Custom React hook to get the previous value of a state or prop.
 *
 * @template T - The type of the value to track.
 * @param {T} value - The current value to track.
 * @returns {T | undefined} - The previous value of the tracked state or prop.
 *
 * @example
 * const [count, setCount] = useState(0);
 * const prevCount = usePrevious(count);
 *
 * useEffect(() => {
 *   console.log("Current count:", count);
 *   console.log("Previous count:", prevCount);
 * }, [count]);
 */
 
export const usePrevious = <T = any>(value: T): T | undefined => {
  const ref = useRef<T | undefined>(undefined)
  useEffect(() => {
    ref.current = value
  }, [value])
  return ref.current
}