Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- akamfoad
- alany411
- alberto
- alex3d
- alexlbr
- AmRo045
- amsal
Expand Down
22 changes: 22 additions & 0 deletions packages/react-router/__tests__/navigate-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,28 @@ describe("<Navigate>", () => {
</div>"
`);
});

it("does not navigate twice in a row in StrictMode", () => {
let { container } = render(
<React.StrictMode>
<MemoryRouter initialEntries={["/page1", "/page2", "/navigate"]}>
<Routes>
<Route path="page1" element={<h1>Page 1</h1>} />
<Route path="page2" element={<h1>Page 2</h1>} />
<Route path="navigate" element={<Navigate to={-1} />} />
</Routes>
</MemoryRouter>
</React.StrictMode>
);

expect(getHtml(container)).toMatchInlineSnapshot(`
"<div>
<h1>
Page 2
</h1>
</div>"
`);
});
});

function getHtml(container: HTMLElement) {
Expand Down
5 changes: 5 additions & 0 deletions packages/react-router/lib/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ export function Navigate({

let dataRouterState = React.useContext(DataRouterStateContext);
let navigate = useNavigate();
let navigateCalledRef = React.useRef(false);

React.useEffect(() => {
// Avoid kicking off multiple navigations if we're in the middle of a
Expand All @@ -217,6 +218,10 @@ export function Navigate({
if (dataRouterState && dataRouterState.navigation.state !== "idle") {
return;
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could probably be removed after navigateCalledRef was added.
No tests fails with this statement removed.

if (navigateCalledRef.current) {
return;
}
navigateCalledRef.current = true;
navigate(to, { replace, state, relative });
});

Expand Down