Documentation Index
Fetch the complete documentation index at: https://mintlify.com/rijvi-mahmud/shaddy/llms.txt
Use this file to discover all available pages before exploring further.
usePrevious is a React hook that captures and returns the value a variable held during the previous render. It works with any type of value — state, props, derived variables — and is fully generic so the returned type always matches the input type. On the very first render it returns undefined, since there is no previous value yet. Common uses include animating between old and new values, detecting the direction of a change (e.g. ascending vs. descending), showing “was / now” diffs in UI, and conditionally triggering effects only when a value actually changed direction.
Installation
Signature
Parameters
The value to track across renders. This can be any type — primitive, object, array, function — and TypeScript infers
T automatically from what you pass. The hook captures a snapshot of this value after each render via a useEffect.Return Value
The value that
value held during the previous render. Returns undefined on the very first render because no prior value exists.Usage
Tracking a Counter
Detecting a Prop Change
Animating a Value Change
Notes
- The hook stores the previous value in a
useRefand updates it inside auseEffect, which runs after rendering. This means the ref always lags one render behind the current value — exactly what “previous” means. - On the initial render
prevCountisundefined. Always guard against this when the distinction matters (prevCount ?? fallbackor an explicitundefinedcheck). - Because the hook uses a plain ref internally, changing the tracked value does not trigger an additional re-render. The previous value is available at no extra rendering cost.
- The generic default is
any, but TypeScript infersTfrom the argument so you get full type safety without an explicit type annotation in most cases.