usePrevious

A hook that returns the previous value of a variable.

Overview

usePrevious stores the value from the previous render. It is commonly used to compare current props or state with their previous values to detect changes or trends.

Demo

State History

Trend Tracker

Visualizes the comparison between the current state and the previous render's state.

Previous
-
Current
0

API Reference

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

Parameters

NameTypeDescription
valueTThe value to track.

Usage Example

import { useState, useEffect } from 'react'
import { usePrevious } from 'react-hooks-ts'
 
function Counter() {
  const [count, setCount] = useState(0)
  const prevCount = usePrevious(count)
 
  useEffect(() => {
    if (prevCount !== undefined && count > prevCount) {
      console.log('Count increased')
    }
  }, [count, prevCount])
 
  return (
    <div>
      <p>Current: {count}</p>
      <p>Previous: {prevCount}</p>
      <button onClick={() => setCount(c => c + 1)}>+</button>
    </div>
  )
}