Add usePreviousValue hook.
This commit is contained in:
parent
6d3aafb15c
commit
8c0c616f15
1 changed files with 19 additions and 0 deletions
|
@ -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;
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue