Skip to content

Commit 32f2c30

Browse files
authored
feat: usePrevious hook (#460)
1 parent 8c08d28 commit 32f2c30

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

packages/fuselage-hooks/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export * from './usePosition';
1616
export * from './usePrefersColorScheme';
1717
export * from './usePrefersReducedData';
1818
export * from './usePrefersReducedMotion';
19+
export * from './usePrevious';
1920
export * from './useResizeObserver';
2021
export * from './useSafely';
2122
export * from './useStableArray';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { FunctionComponent, createElement, StrictMode, useState } from 'react';
2+
import { render } from 'react-dom';
3+
import { act } from 'react-dom/test-utils';
4+
5+
import { usePrevious } from '.';
6+
7+
it('returns previous values', () => {
8+
let previous: number | undefined;
9+
let current: number;
10+
let increment: () => void;
11+
12+
const TestComponent: FunctionComponent = () => {
13+
const [count, setCount] = useState(0);
14+
previous = usePrevious(count);
15+
16+
current = count;
17+
increment = () => {
18+
setCount((count) => count + 1);
19+
};
20+
21+
return null;
22+
};
23+
24+
act(() => {
25+
render(
26+
createElement(StrictMode, {}, createElement(TestComponent)),
27+
document.createElement('div')
28+
);
29+
});
30+
31+
expect(current).toBe(0);
32+
expect(previous).toBe(undefined);
33+
34+
act(increment);
35+
36+
expect(current).toBe(1);
37+
expect(previous).toBe(0);
38+
39+
act(increment);
40+
41+
expect(current).toBe(2);
42+
expect(previous).toBe(1);
43+
});
+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { useEffect, useRef } from 'react';
2+
3+
export const usePrevious = <T>(value: T): T | undefined => {
4+
const ref = useRef<T>();
5+
6+
useEffect(() => {
7+
ref.current = value;
8+
});
9+
10+
return ref.current;
11+
};

0 commit comments

Comments
 (0)