React

Read Graft content from React code that runs in the browser.

Frameworks4 min read

@usegraft/sdk-react gives you React hooks that read content over HTTP. Use it when your React code runs in the browser and cannot open the index itself:

  • a single-page app built with Vite, or
  • an interactive component that loads content after the page is on screen, such as a live search box or a filter.

The hooks call Graft's Content API, so something has to serve it: graft serve, or the Content API handler mounted in your own backend. The browser never receives a database connection or the index file.

Before you start, you need a graft.config.ts and a running Content API. By the end of this page you have a typed client, a component that shows one document, and a search box.

Install

npm i @usegraft/sdk-react
pnpm add @usegraft/sdk-react
bun add @usegraft/sdk-react

It needs React 18 or 19.

Create the client and hooks

Create the client once, pointed at your Content API, and build the hooks from it:

src/graft.ts
import { createGraft, createGraftHooks } from "@usegraft/sdk-react";
import { collections } from "../graft.config";

export const graft = createGraft({
  endpoint: "https://cms.example.com/api/content/v1",
  collections,
});

export const { GraftProvider, useContent, useContentList, useContentSearch } =
  createGraftHooks(graft);

The hooks are typed from your own graft.config.ts, so post.data.title is checked at compile time. There is no code generation step and no schema to download.

The hooks read from this client by default, so you do not need a provider. Wrap a part of your app in <GraftProvider graft={other}> only when it should read from somewhere else, such as a preview deployment's endpoint or a fake client in tests.

Show one document

useContent reads a document by collection and slug. It returns loading, error, data, and a refresh function to try again:

src/BlogPost.tsx
import { useContent } from "./graft";

export function BlogPost({ slug }: { slug: string }) {
  const { data: post, loading, error, refresh } = useContent("posts", slug);

  if (loading) return <p>Loading…</p>;
  if (error) {
    return (
      <p>
        Could not load this post. <button onClick={refresh}>Try again</button>
      </p>
    );
  }
  if (!post) return <p>Post not found.</p>;

  return (
    <article>
      <h1>{post.data.title}</h1>
      <pre>{post.body}</pre>
    </article>
  );
}

data is null when the collection has no document with that slug, so a missing post is not an error. post.body is the Markdown or MDX source as written. Render it with your own Markdown or MDX renderer. When a server prepared the body with prepareMdx, as the React Router and TanStack Start adapters do, render the result with MdxContent from @usegraft/sdk-react/mdx.

useContentSearch runs a full-text search in one collection, best match first. An empty query returns no results and sends no request, so you can pass the input's value straight in:

src/SearchBox.tsx
import { useState } from "react";
import { useContentSearch } from "./graft";

export function SearchBox() {
  const [query, setQuery] = useState("");
  const { data: hits, loading, error } = useContentSearch("docs", query, { limit: 10 });

  return (
    <div>
      <input type="search" value={query} onChange={(e) => setQuery(e.target.value)} />
      {loading && <p>Searching…</p>}
      {error && <p>Search failed.</p>}
      {query.trim() !== "" && hits?.length === 0 && <p>No results.</p>}
      <ul>
        {hits?.map((hit) => (
          <li key={hit.slug}>
            <a href={`/docs/${hit.slug}`}>{hit.data.title}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

Each change to a non-blank query sends one request. For a busy endpoint, debounce the input before you pass it on.

Each hit also has a snippet: the matching text with each match wrapped in <b>…</b>. The tags come from the index and the rest of the snippet is your content, so do not insert it with dangerouslySetInnerHTML unless you trust everyone who can write content. Split on the tags instead:

function Snippet({ text }: { text: string }) {
  return (
    <p>
      {text.split(/<b>([\s\S]*?)<\/b>/g).map((part, i) =>
        i % 2 === 1 ? <mark key={i}>{part}</mark> : part,
      )}
    </p>
  );
}

Use TanStack Query or SWR instead

The hooks keep the latest result in component state, and nothing more. If you want shared caching, retries, or background refresh, call the client from your data library instead. It has the same methods: getContent, listContent, and searchContent.

import { useQuery } from "@tanstack/react-query";
import { graft } from "./graft";

export function usePost(slug: string) {
  return useQuery({
    queryKey: ["posts", slug],
    queryFn: () => graft.getContent("posts", slug),
  });
}

What the browser cannot do

  • Reach the database. The client only speaks HTTP. It has no option for a database connection, so a connection string cannot end up in your bundle.
  • Choose a branch. Each Content API endpoint serves one branch, set by the server. On an endpoint-backed handle, passing branch to createGraft, to a read, or to a read through graft.client throws CONFIG_INVALID, even branch: "main". A handle built on your own index takes branch as usual. To read a preview branch, point a second client at the preview deployment's endpoint.
  • Render on the server. During server rendering the hooks return their loading state. Content that must be in the first HTML belongs in your framework's server package. A module that calls createGraft with a same-origin endpoint such as /api/content/v1 can still be imported on the server: the client is built on the first read, and only a read there fails.

Next steps

  • Content API shows how to serve the endpoint, with graft serve or mounted in your own backend.
  • Schema defines the collections your hooks are typed from.
  • SDK reference lists every method on the client.