Skip to content

Commit

Permalink
[@mantine/hooks] use-previous: Init hook (#2313)
Browse files Browse the repository at this point in the history
  • Loading branch information
kabeer05 committed Sep 6, 2022
1 parent 21f0117 commit 265bb66
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 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<T>(value: T): T
```
1 change: 1 addition & 0 deletions src/mantine-hooks/src/index.ts
Expand Up @@ -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';
Expand Down
19 changes: 19 additions & 0 deletions 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);
});
});
11 changes: 11 additions & 0 deletions src/mantine-hooks/src/use-previous/use-previous.ts
@@ -0,0 +1,11 @@
import { useEffect, useRef } from 'react';

export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T>();

useEffect(() => {
ref.current = value;
}, [value]);

return ref.current;
}

0 comments on commit 265bb66

Please sign in to comment.