Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[@mantine/hooks] use-previous: Implement hook #2313

Merged
merged 1 commit into from Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
}