From d608fd3cb26dc9f70f1930d132f601c621014d26 Mon Sep 17 00:00:00 2001 From: Wonsuk Choi Date: Tue, 6 Aug 2024 15:25:01 +0900 Subject: [PATCH] =?UTF-8?q?feat(ui/hooks):=20usePrevious=20hook=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/ui/src/hooks/index.ts | 1 + packages/ui/src/hooks/use-previous.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 packages/ui/src/hooks/use-previous.ts diff --git a/packages/ui/src/hooks/index.ts b/packages/ui/src/hooks/index.ts index cce26e9..fa12a0c 100644 --- a/packages/ui/src/hooks/index.ts +++ b/packages/ui/src/hooks/index.ts @@ -3,5 +3,6 @@ export { useBoolean } from './use-boolean'; export { useDisclosure } from './use-disclosure'; export { useLayoutEffect } from './use-layout-effect'; export { usePosition, type Placement } from './use-position'; +export { usePrevious } from './use-previous'; export { useScroll } from './use-scroll'; export { useWindowDimension } from './use-window-dimension'; diff --git a/packages/ui/src/hooks/use-previous.ts b/packages/ui/src/hooks/use-previous.ts new file mode 100644 index 0000000..dedf146 --- /dev/null +++ b/packages/ui/src/hooks/use-previous.ts @@ -0,0 +1,14 @@ +import { useMemo, useRef } from 'react'; + +export function usePrevious(value: T) { + const ref = useRef({ value, previous: value }); + + return useMemo(() => { + if (ref.current.value !== value) { + ref.current.previous = ref.current.value; + ref.current.value = value; + } + + return ref.current.previous; + }, [value]); +}