返回 Skill 列表
extension
分类: 开发与工程无需 API Key

solidstart-client-only

SolidStart clientOnly:仅在客户端渲染组件/页面,绕过SSR以使用浏览器API(如window、document),并支持带有回退的动态导入。

person作者: jakexiaohubgithub

SolidStart clientOnly

The clientOnly function renders components or pages exclusively on the client side, bypassing SSR.

Component Usage

  1. Create separate file for client-only component:
// ClientOnlyComponent.tsx
export default function ClientOnlyComponent() {
  const location = document.location.href;
  return <div>Current URL: {location}</div>;
}
  1. Import with clientOnly:
import { clientOnly } from "@solidjs/start";

const ClientOnlyComp = clientOnly(() => import("./ClientOnlyComponent"));

export default function IsomorphicComponent() {
  return <ClientOnlyComp />;
}
  1. Optional fallback:
<ClientOnlyComp fallback={<div>Loading...</div>} />

Page-Level Usage

Disable SSR for entire page:

// routes/page.tsx
import { clientOnly } from "@solidjs/start";

export default clientOnly(async () => ({ default: Page }), { lazy: true });

function Page() {
  // This code runs only on client
  return <div>Client-only page content</div>;
}

Parameters

fn: () => Promise<{ default: () => JSX.Element }>

  • Function that dynamically imports component

options: { lazy?: boolean }

  • lazy: true (default) - Lazy load component
  • lazy: false - Eager loading

props: Record<string, any> & { fallback?: JSX.Element }

  • Props passed to component
  • Optional fallback for loading state

Use Cases

  • Browser APIs (window, document, localStorage)
  • Third-party widgets (maps, charts)
  • DOM manipulation
  • Avoiding SSR hydration issues
  • Code that can't run on server

Best Practices

  1. Isolate client-only logic in separate files
  2. Provide meaningful fallbacks for loading states
  3. Use sparingly - prefer SSR when possible
  4. Consider progressive enhancement where possible