2019-11-08 16:30:11 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2019-11-06 18:25:37 +00:00
|
|
|
import { useRef, useEffect } from 'react';
|
|
|
|
|
2021-03-10 15:03:26 +00:00
|
|
|
interface Validation< T > {
|
|
|
|
( value: T, previousValue: T | undefined ): boolean;
|
|
|
|
}
|
2019-11-06 18:25:37 +00:00
|
|
|
/**
|
2019-11-19 15:14:34 +00:00
|
|
|
* Use Previous based on https://usehooks.com/usePrevious/.
|
2019-12-10 17:17:46 +00:00
|
|
|
*
|
2022-04-08 13:47:19 +00:00
|
|
|
* @param {*} value
|
2019-11-19 15:14:34 +00:00
|
|
|
* @param {Function} [validation] Function that needs to validate for the value
|
|
|
|
* to be updated.
|
2019-11-06 18:25:37 +00:00
|
|
|
*/
|
2021-03-10 15:03:26 +00:00
|
|
|
export function usePrevious< T >(
|
|
|
|
value: T,
|
|
|
|
validation?: Validation< T >
|
|
|
|
): T | undefined {
|
|
|
|
const ref = useRef< T >();
|
2019-11-06 18:25:37 +00:00
|
|
|
|
|
|
|
useEffect( () => {
|
2019-11-19 15:14:34 +00:00
|
|
|
if (
|
|
|
|
ref.current !== value &&
|
|
|
|
( ! validation || validation( value, ref.current ) )
|
|
|
|
) {
|
|
|
|
ref.current = value;
|
|
|
|
}
|
2020-10-27 15:39:08 +00:00
|
|
|
}, [ value, validation ] );
|
2019-11-06 18:25:37 +00:00
|
|
|
|
|
|
|
return ref.current;
|
2021-03-10 15:03:26 +00:00
|
|
|
}
|