Skip to content

Commit

Permalink
Memoize result from useMatch() between renders (#8431)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim Dorr <timdorr@users.noreply.github.com>
  • Loading branch information
jonkoops and timdorr committed Dec 3, 2021
1 parent 1108f1c commit 53847bb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
43 changes: 42 additions & 1 deletion packages/react-router/__tests__/useMatch-test.tsx
@@ -1,6 +1,6 @@
import * as React from "react";
import * as TestRenderer from "react-test-renderer";
import { MemoryRouter, Routes, Route, useMatch } from "react-router";
import { MemoryRouter, PathMatch, Routes, Route, useMatch } from "react-router";

function ShowMatch({ pattern }: { pattern: string }) {
return <pre>{JSON.stringify(useMatch(pattern), null, 2)}</pre>;
Expand Down Expand Up @@ -93,4 +93,45 @@ describe("useMatch", () => {
`);
});
});

describe("when re-rendered with the same URL", () => {
it("returns the memoized match", () => {
let path = "/home";
let match: PathMatch<string>;
let firstMatch: PathMatch<string>;

function HomePage() {
match = useMatch(path);

if (!firstMatch) {
firstMatch = match;
}

return null;
}

let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path={path} element={<HomePage />} />
</Routes>
</MemoryRouter>
);
});

TestRenderer.act(() => {
renderer.update(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path={path} element={<HomePage />} />
</Routes>
</MemoryRouter>
);
});

expect(match).toBe(firstMatch);
});
});
});
3 changes: 2 additions & 1 deletion packages/react-router/index.tsx
Expand Up @@ -431,7 +431,8 @@ export function useMatch<ParamKey extends string = string>(
`useMatch() may be used only in the context of a <Router> component.`
);

return matchPath(pattern, useLocation().pathname);
let { pathname } = useLocation();
return React.useMemo(() => matchPath(pattern, pathname), [pathname, pattern]);
}

/**
Expand Down

0 comments on commit 53847bb

Please sign in to comment.