Add usePrevious hook.

master
Auri 2021-08-24 19:47:19 -07:00
parent a45a9320d1
commit e5af84877d
2 changed files with 16 additions and 0 deletions

View File

@ -9,6 +9,8 @@ export { default as useMediaMatches } from './useMediaMatches';
export type { MessagingCallback, MessagingCallbacks, MessagingOptions } from './useMessaging';
export { default as useMessaging } from './useMessaging';
export { default as usePrevious } from './usePrevious';
export { default as useRerender } from './useRerender';
export { default as useStoredState } from './useStoredState';

14
src/usePrevious.ts Normal file
View File

@ -0,0 +1,14 @@
import { useEffect, useRef } from 'react';
/**
* Accepts a value, stores it, and then returns it on the next render.
*
* @param value - The current value.
* @returns the previous value, or undefined if this is the first render.
*/
export default function usePrevious<T = any>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => { ref.current = value; }, [ value ]);
return ref.current;
};