Skip to content

Commit

Permalink
fix: memoize useNavigation hook
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Oct 6, 2021
1 parent b256f8e commit e52efbc
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 11 deletions.
55 changes: 46 additions & 9 deletions src/hooks/__tests__/useNavigation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,27 @@ import { RouterProvider } from '../../components/RouterProvider';
import type { RouterContextProps } from '../../types';
import { useNavigation } from '../useNavigation';

const ContextWrapper = ({ children }: { children: ReactNode }) => {
const defaultMockHistory = {
block: 'mockHistoryBlock',
go: 'mockHistoryGo',
goBack: 'mockHistoryBack',
goForward: 'mockHistoryForward',
push: 'mockHistoryPush',
replace: 'mockHistoryReplace',
};

const ContextWrapper = ({
children,
history = defaultMockHistory,
}: {
children?: ReactNode;
history?: unknown;
}) => {
return (
<RouterProvider
router={
{
history: {
block: 'mockHistoryBlock',
go: 'mockHistoryGo',
goBack: 'mockHistoryBack',
goForward: 'mockHistoryForward',
push: 'mockHistoryPush',
replace: 'mockHistoryReplace',
},
history,
} as unknown as RouterContextProps
}
>
Expand Down Expand Up @@ -48,4 +56,33 @@ describe('useNavigation()', () => {
replace: 'mockHistoryReplace',
});
});

it('should return memoized function', () => {
const { result, rerender } = renderHook(() => useNavigation(), {
wrapper: ContextWrapper,
});

const firstResult = result.current;

rerender();

expect(firstResult).toEqual(result.current);
});

it('should mutate navigation if history object changes', () => {
const { result, rerender } = renderHook(() => useNavigation(), {
wrapper: ContextWrapper,
});

const firstResult = result.current;

rerender({
history: {
...defaultMockHistory,
block: 'foo',
},
});

expect(firstResult).not.toEqual(result.current);
});
});
7 changes: 5 additions & 2 deletions src/hooks/useNavigation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { History } from 'history';
import { useContext } from 'react';
import { useContext, useMemo } from 'react';
import { isRouterContext, RouterContext } from '../context/RouterContext';
import type { RouterContextProps, State } from '../types';

Expand All @@ -23,5 +23,8 @@ export const useNavigation = <S extends State = State>(): UseNavigation<S> => {

const { goBack, block, goForward, go, push, replace } = context.history;

return { back: goBack, block, forward: goForward, go, push, replace };
return useMemo(
() => ({ back: goBack, block, forward: goForward, go, push, replace }),
[goBack, block, goForward, go, push, replace]
);
};

0 comments on commit e52efbc

Please sign in to comment.