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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions packages/react-router/__tests__/useNavigate-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,77 @@ describe("useNavigate", () => {
]
`);
});

it("transitions to the new location when called immediately", () => {
const Home = React.forwardRef(function Home(_props, ref) {
let navigate = useNavigate();

React.useImperativeHandle(ref, () => ({
navigate: () => navigate("/about")
}))

return null
})

let homeRef;

let renderer: TestRenderer.ReactTestRenderer;
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home ref={(ref) => homeRef = ref} />} />
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>
);

TestRenderer.act(() => {
homeRef.navigate();
})

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<h1>
About
</h1>
`);
});

it("allows navigation in child useEffects", () => {
function Child({ onChildRendered }) {

React.useEffect(() => {
onChildRendered();
});

return null;
}

function Parent() {
let navigate = useNavigate();

let onChildRendered = React.useCallback(() => navigate("/about"), []);

return <Child onChildRendered={onChildRendered} />;
}

let renderer: TestRenderer.ReactTestRenderer;
TestRenderer.act(() => {
renderer = TestRenderer.create(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Parent />} />
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>
);
});

expect(renderer.toJSON()).toMatchInlineSnapshot(`
<h1>
About
</h1>
`);
});

describe("with state", () => {
it("adds the state to location.state", () => {
Expand Down
4 changes: 1 addition & 3 deletions packages/react-router/lib/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ export function useNavigate(): NavigateFunction {
);

let activeRef = React.useRef(false);
React.useEffect(() => {
React.useLayoutEffect(() => {
activeRef.current = true;
});

Expand All @@ -205,8 +205,6 @@ export function useNavigate(): NavigateFunction {
`your component is first rendered.`
);

if (!activeRef.current) return;

if (typeof to === "number") {
navigator.go(to);
return;
Expand Down