Skip to content

Commit

Permalink
feat: usePrevious hook (#460)
Browse files Browse the repository at this point in the history
  • Loading branch information
tassoevan authored May 28, 2021
1 parent 8c08d28 commit 32f2c30
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/fuselage-hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export * from './usePosition';
export * from './usePrefersColorScheme';
export * from './usePrefersReducedData';
export * from './usePrefersReducedMotion';
export * from './usePrevious';
export * from './useResizeObserver';
export * from './useSafely';
export * from './useStableArray';
Expand Down
43 changes: 43 additions & 0 deletions packages/fuselage-hooks/src/usePrevious.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { FunctionComponent, createElement, StrictMode, useState } from 'react';
import { render } from 'react-dom';
import { act } from 'react-dom/test-utils';

import { usePrevious } from '.';

it('returns previous values', () => {
let previous: number | undefined;
let current: number;
let increment: () => void;

const TestComponent: FunctionComponent = () => {
const [count, setCount] = useState(0);
previous = usePrevious(count);

current = count;
increment = () => {
setCount((count) => count + 1);
};

return null;
};

act(() => {
render(
createElement(StrictMode, {}, createElement(TestComponent)),
document.createElement('div')
);
});

expect(current).toBe(0);
expect(previous).toBe(undefined);

act(increment);

expect(current).toBe(1);
expect(previous).toBe(0);

act(increment);

expect(current).toBe(2);
expect(previous).toBe(1);
});
11 changes: 11 additions & 0 deletions packages/fuselage-hooks/src/usePrevious.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { useEffect, useRef } from 'react';

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

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

return ref.current;
};

0 comments on commit 32f2c30

Please sign in to comment.