diff --git a/docs/src/docs/hooks/use-previous.mdx b/docs/src/docs/hooks/use-previous.mdx new file mode 100644 index 00000000000..2015a74d622 --- /dev/null +++ b/docs/src/docs/hooks/use-previous.mdx @@ -0,0 +1,30 @@ +--- +group: 'mantine-hooks' +package: '@mantine/hooks' +category: 'state' +title: 'use-previous' +order: 1 +slug: /hooks/use-previous/ +description: 'Get the previous value of a state' +import: "import { usePrevious } from '@mantine/hooks';" +docs: 'hooks/use-previous.mdx' +source: 'mantine-hooks/src/use-previous/use-previous.ts' +--- + +## Usage + +`use-previous` hook stores the previous value of a state in a ref. Returns undefined on initial render and the previous value of a state after rerender. + +Arguments: + +- `value`: The value to store in the ref. + +Returns: + +- `previousValue`: The previous value of the state. + +## Definition + +```tsx +function usePrevious(value: T): T +``` diff --git a/src/mantine-hooks/src/index.ts b/src/mantine-hooks/src/index.ts index 17605db685e..933a09fc1de 100644 --- a/src/mantine-hooks/src/index.ts +++ b/src/mantine-hooks/src/index.ts @@ -51,6 +51,7 @@ export { useFocusWithin } from './use-focus-within/use-focus-within'; export { useNetwork } from './use-network/use-network'; export { useTimeout } from './use-timeout/use-timeout'; export { useTextSelection } from './use-text-selection/use-text-selection'; +export { usePrevious } from './use-previous/use-previous'; export type { UseMovePosition } from './use-move/use-move'; export type { OS } from './use-os/use-os'; diff --git a/src/mantine-hooks/src/use-previous/use-previous.test.ts b/src/mantine-hooks/src/use-previous/use-previous.test.ts new file mode 100644 index 00000000000..f1735df190c --- /dev/null +++ b/src/mantine-hooks/src/use-previous/use-previous.test.ts @@ -0,0 +1,19 @@ +import { renderHook } from '@testing-library/react'; +import { usePrevious } from './use-previous'; + +describe('@mantine/hooks/use-previous', () => { + it('returns undefined on intial render', () => { + const hook = renderHook(() => usePrevious(1)); + expect(hook.result.current).toBeUndefined(); + }); + + it('returns the previous value after update', () => { + const hook = renderHook(({ state }) => usePrevious(state), { initialProps: { state: 1 } }); + + hook.rerender({ state: 2 }); + expect(hook.result.current).toBe(1); + + hook.rerender({ state: 4 }); + expect(hook.result.current).toBe(2); + }); +}); diff --git a/src/mantine-hooks/src/use-previous/use-previous.ts b/src/mantine-hooks/src/use-previous/use-previous.ts new file mode 100644 index 00000000000..b6d9f759830 --- /dev/null +++ b/src/mantine-hooks/src/use-previous/use-previous.ts @@ -0,0 +1,11 @@ +import { useEffect, useRef } from 'react'; + +export function usePrevious(value: T): T | undefined { + const ref = useRef(); + + useEffect(() => { + ref.current = value; + }, [value]); + + return ref.current; +}