Add usePreviousValue hook.

This commit is contained in:
Madeorsk 2024-07-13 16:37:24 +02:00
parent 6d3aafb15c
commit 8c0c616f15
Signed by: Madeorsk
SSH key fingerprint: SHA256:J9G0ofIOLKf7kyS2IfrMqtMaPdfsk1W02+oGueZzDDU

View file

@ -1,3 +1,4 @@
import {useEffect, useRef} from "react";
export type Modify<T, R> = Omit<T, keyof R> & R; export type Modify<T, R> = Omit<T, keyof R> & R;
@ -31,3 +32,21 @@ export function normalizeString(str: string): string
.replace?.(/[\u0300-\u036f]/g, "") .replace?.(/[\u0300-\u036f]/g, "")
: ""; : "";
} }
/**
* Get the previous value of a given value.
* @param currentValue The current value.
*/
export function usePreviousValue<T>(currentValue: T): T
{
// Get the reference to the previous value.
const ref = useRef<T>();
// If the value has changed, saving it in the reference after rendering.
useEffect(() => {
ref.current = currentValue;
}, [currentValue]);
// Get the previous value.
return ref?.current ?? undefined;
}