From 8c0c616f1523d5e93ab5c408c5be1c4ebb6884bd Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Sat, 13 Jul 2024 16:37:24 +0200 Subject: [PATCH] Add usePreviousValue hook. --- src/Utils.tsx | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/Utils.tsx b/src/Utils.tsx index 53412de..6147e56 100644 --- a/src/Utils.tsx +++ b/src/Utils.tsx @@ -1,3 +1,4 @@ +import {useEffect, useRef} from "react"; export type Modify = Omit & R; @@ -31,3 +32,21 @@ export function normalizeString(str: string): string .replace?.(/[\u0300-\u036f]/g, "") : ""; } + +/** + * Get the previous value of a given value. + * @param currentValue The current value. + */ +export function usePreviousValue(currentValue: T): T +{ + // Get the reference to the previous value. + const ref = useRef(); + + // 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; +}