R
fn

usePrevious

v0.0.15testeddemo

Track the previous value of a ref, getter, or reactive source.

Examples

ts
const count = ref(0);
const prev = usePrevious(count);
count.value = 1; // prev.value === 0
ts
const count = ref(0);
const prev = usePrevious(count, -1); // prev.value === -1 until count changes
ts
const state = reactive({ n: 1 });
const prev = usePrevious(() => ({ ...state }), undefined, { deep: true });

Demo

Loading demo…

Signatures

ts
export function usePrevious<T>(value: MaybeRefOrGetter<T>, initialValue: T, options?: UsePreviousOptions): Readonly<ShallowRef<T>>;
ts
export function usePrevious<T>(value: MaybeRefOrGetter<T>, initialValue?: undefined, options?: UsePreviousOptions): Readonly<ShallowRef<T | undefined>>;

Type Parameters

T

Parameters

ParameterTypeDescription
valueMaybeRefOrGetter<T>The source value to track
initialValue?T | undefinedThe initial previous value, or an options object
options?UsePreviousOptionsThe initial previous value, or an options object

Returns

Readonly<ShallowRef<T | undefined>>The previous value of the source