Typed HooksGetting StartedusePrevious

usePrevious

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

⚠️ This content is not available in your language yet.

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

Installation

pnpm dlx shadcn@latest add https://shaddy-docs.vercel.app/r/use-previous

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.