Skip to content
Merged
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
106 changes: 55 additions & 51 deletions packages/docs/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,76 +20,80 @@ import { ClientApp } from "./ClientApp.js";

const routes = [
route({
path: "/funstack-router",
component: Layout,
children: [
route({
path: "/",
component: HomePage,
}),
route({
path: "/getting-started",
component: GettingStartedPage,
}),
route({
path: "/learn",
component: LearnPage,
path: "/funstack-router",
children: [
route({
path: "/",
component: LearnIndexPage,
component: HomePage,
}),
route({
path: "/navigation-api",
component: LearnNavigationApiPage,
path: "/getting-started",
component: GettingStartedPage,
}),
route({
path: "/nested-routes",
component: LearnNestedRoutesPage,
path: "/learn",
component: LearnPage,
children: [
route({
path: "/",
component: LearnIndexPage,
}),
route({
path: "/navigation-api",
component: LearnNavigationApiPage,
}),
route({
path: "/nested-routes",
component: LearnNestedRoutesPage,
}),
route({
path: "/type-safety",
component: LearnTypeSafetyPage,
}),
route({
path: "/server-side-rendering",
component: LearnSsrPage,
}),
],
}),
route({
path: "/type-safety",
component: LearnTypeSafetyPage,
path: "/api",
component: ApiReferencePage,
children: [
route({
path: "/",
component: ApiReferenceIndexPage,
}),
route({
path: "/components",
component: ApiComponentsPage,
}),
route({
path: "/hooks",
component: ApiHooksPage,
}),
route({
path: "/utilities",
component: ApiUtilitiesPage,
}),
route({
path: "/types",
component: ApiTypesPage,
}),
],
}),
route({
path: "/server-side-rendering",
component: LearnSsrPage,
}),
],
}),
route({
path: "/api",
component: ApiReferencePage,
children: [
route({
path: "/",
component: ApiReferenceIndexPage,
path: "/examples",
component: ExamplesPage,
}),
route({
path: "/components",
component: ApiComponentsPage,
}),
route({
path: "/hooks",
component: ApiHooksPage,
}),
route({
path: "/utilities",
component: ApiUtilitiesPage,
}),
route({
path: "/types",
component: ApiTypesPage,
component: NotFoundPage,
}),
],
}),
route({
path: "/examples",
component: ExamplesPage,
}),
route({
component: NotFoundPage,
}),
],
}),
];
Expand Down
5 changes: 3 additions & 2 deletions packages/docs/src/components/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";

import { useState } from "react";
import { Outlet, useLocation } from "@funstack/router";
import { Outlet, useLocationSSR } from "@funstack/router";

const navItems = [
{ path: "/funstack-router/", label: "Home" },
Expand All @@ -12,10 +12,11 @@ const navItems = [
];

export function Layout() {
const location = useLocation();
const location = useLocationSSR();
const [isMenuOpen, setIsMenuOpen] = useState(false);

const isActive = (path: string) => {
if (location === null) return false;
// Handle API Reference section (match any /api/* path)
if (path === "/funstack-router/api") {
return location.pathname.startsWith("/funstack-router/api");
Expand Down
38 changes: 38 additions & 0 deletions packages/docs/src/pages/ApiHooksPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,44 @@ function MyComponent() {
}`}</CodeBlock>
</article>

<article className="api-item">
<h3>
<code>useLocationSSR()</code>
</h3>
<p>
Returns the current location object, or <code>null</code> when the URL
is not available (e.g. during SSR). This is the SSR-safe alternative
to <code>useLocation()</code>.
</p>
<CodeBlock language="tsx">{`import { useLocationSSR } from "@funstack/router";

function AppShell() {
const location = useLocationSSR();

// location is null during SSR, Location object after hydration
const isActive = (path: string) => {
if (location === null) return false;
return location.pathname === path;
};

return (
<nav>
<a className={isActive("/") ? "active" : ""} href="/">Home</a>
<a className={isActive("/about") ? "active" : ""} href="/about">About</a>
</nav>
);
}`}</CodeBlock>
<h4>Return Value</h4>
<ul>
<li>
<code>Location | null</code> &mdash; The current location object
with <code>pathname</code>, <code>search</code>, and{" "}
<code>hash</code> properties, or <code>null</code> during SSR when
no URL is available.
</li>
</ul>
</article>

<article className="api-item">
<h3>
<code>useSearchParams()</code>
Expand Down
4 changes: 4 additions & 0 deletions packages/docs/src/pages/ApiReferenceIndexPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ export function ApiReferenceIndexPage() {
<li>
<code>useLocation()</code> — Current location object
</li>
<li>
<code>useLocationSSR()</code> — SSR-safe current location (returns{" "}
<code>null</code> during SSR)
</li>
<li>
<code>useSearchParams()</code> — Search query management
</li>
Expand Down
21 changes: 16 additions & 5 deletions packages/docs/src/pages/LearnSsrPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,27 @@ useLocation();
useSearchParams();
// Error: "useSearchParams: URL is not available during SSR."`}</CodeBlock>
<p>
To avoid these errors, only use URL-dependent hooks in components
rendered by path-based routes. Since path-based routes only render
after hydration (when the URL is available), these hooks will work
correctly:
To avoid these errors, either use URL-dependent hooks only in
components rendered by path-based routes, or use the SSR-safe{" "}
<code>useLocationSSR()</code> hook which returns <code>null</code>{" "}
instead of throwing when the URL is unavailable:
</p>
<CodeBlock language="tsx">{`// ✗ Bad: AppShell renders during SSR, useLocation will throw
function AppShell() {
const location = useLocation(); // Throws during SSR!
return <div>{/* ... */}</div>;
}

// ✓ Good: Use useLocationSSR in components that render during SSR
function AppShell() {
const location = useLocationSSR(); // Returns null during SSR
const isActive = (path: string) => {
if (location === null) return false;
return location.pathname === path;
};
return <nav>{/* ... */}</nav>;
}

// ✓ Good: HomePage only renders after hydration (has a path)
function HomePage() {
const location = useLocation(); // Safe — URL is available
Expand Down Expand Up @@ -149,7 +159,8 @@ function HomePage() {
</li>
<li>
Avoid <code>useLocation</code> and <code>useSearchParams</code> in
components that render during SSR
components that render during SSR; use <code>useLocationSSR</code>{" "}
instead when you need location information in the app shell
</li>
<li>
This two-stage model keeps SSR output lightweight while enabling
Expand Down
68 changes: 68 additions & 0 deletions packages/router/src/__tests__/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import { Suspense, type ReactNode } from "react";
import { Router } from "../Router.js";
import { useNavigate } from "../hooks/useNavigate.js";
import { useLocation } from "../hooks/useLocation.js";
import { useLocationSSR } from "../hooks/useLocationSSR.js";
import { useSearchParams } from "../hooks/useSearchParams.js";
import { useIsPending } from "../hooks/useIsPending.js";
import { setupNavigationMock, cleanupNavigationMock } from "./setup.js";
import { RouterContext } from "../context/RouterContext.js";
import type { RouteDefinition } from "../route.js";

describe("hooks", () => {
Expand Down Expand Up @@ -131,6 +133,72 @@ describe("hooks", () => {
});
});

describe("useLocationSSR", () => {
it("returns current location when URL is available", () => {
mockNavigation = setupNavigationMock(
"http://localhost/page?foo=bar#section",
);

function TestComponent() {
const location = useLocationSSR();
return (
<div>
<span data-testid="pathname">{location?.pathname}</span>
<span data-testid="search">{location?.search}</span>
<span data-testid="hash">{location?.hash}</span>
</div>
);
}

const routes: RouteDefinition[] = [
{ path: "/page", component: TestComponent },
];

render(<Router routes={routes} />);

expect(screen.getByTestId("pathname").textContent).toBe("/page");
expect(screen.getByTestId("search").textContent).toBe("?foo=bar");
expect(screen.getByTestId("hash").textContent).toBe("#section");
});

it("returns null during SSR (url is null)", () => {
let capturedLocation: ReturnType<typeof useLocationSSR> | undefined;

function TestComponent() {
capturedLocation = useLocationSSR();
return <div>test</div>;
}

const ssrContextValue = {
locationEntry: null,
url: null,
isPending: false,
navigate: () => {},
navigateAsync: async () => {},
updateCurrentEntryState: () => {},
};

render(
<RouterContext.Provider value={ssrContextValue}>
<TestComponent />
</RouterContext.Provider>,
);

expect(capturedLocation).toBeNull();
});

it("throws when used outside Router", () => {
function TestComponent() {
useLocationSSR();
return null;
}

expect(() => render(<TestComponent />)).toThrow(
"useLocationSSR must be used within a Router",
);
});
});

describe("useSearchParams", () => {
it("returns current search params", () => {
mockNavigation = setupNavigationMock(
Expand Down
25 changes: 25 additions & 0 deletions packages/router/src/hooks/useLocationSSR.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useContext, useMemo } from "react";
import { RouterContext } from "../context/RouterContext.js";
import type { Location } from "../types.js";

/**
* Returns the current location object, or `null` when the URL is not available (e.g. during SSR).
*/
export function useLocationSSR(): Location | null {
const context = useContext(RouterContext);

if (!context) {
throw new Error("useLocationSSR must be used within a Router");
}

const { url } = context;

return useMemo(() => {
if (url === null) return null;
return {
pathname: url.pathname,
search: url.search,
hash: url.hash,
};
}, [url]);
}
1 change: 1 addition & 0 deletions packages/router/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export { Outlet } from "./Outlet.js";
// Hooks
export { useNavigate } from "./hooks/useNavigate.js";
export { useLocation } from "./hooks/useLocation.js";
export { useLocationSSR } from "./hooks/useLocationSSR.js";
export { useSearchParams } from "./hooks/useSearchParams.js";
export { useBlocker, type UseBlockerOptions } from "./hooks/useBlocker.js";
export { useRouteParams } from "./hooks/useRouteParams.js";
Expand Down