SDK & Integration

Reading Kookee content with React hooks

Mis à jour 226 vues

@kookee/react gives you a hook for every Kookee module — blog, pages, help center, FAQ, changelog, announcements and feedback, plus generic hooks that read any of them by type. The hooks fetch and hand back data; you write the markup.

They are headless and carry no query layer of their own, so nothing about how your app renders or caches is decided for you.

Would you rather not write the markup? The same package ships ready-made, server-rendered components for a blog, a changelog, a help center and a roadmap. They take the data you fetched as props, so a hook's data can go straight into one. See React components for your blog, changelog and help center.

Install

Bash
npm install @kookee/react @kookee/sdk

@kookee/sdk is a peer dependency and is not installed for you, and neither are react and react-dom (18 or 19). If you only want the plain TypeScript client with no React, see Installing the SDK.

Wrap your app once

Every hook reads its client from a provider, so mount one at the root:

tsx
import { KookeeProvider } from '@kookee/react';

export function Root() {
  return (
    <KookeeProvider config={{ apiKey: import.meta.env.VITE_KOOKEE_API_KEY }} locale="en">
      <App />
    </KookeeProvider>
  );
}
  • config — apiKey or projectId, plus an optional baseUrl if you point at something other than the public API.

  • locale — the default locale for every hook below it. A locale passed to an individual hook overrides it.

The client is built once and shared, and it is memoized on the values inside config rather than on the object identity — so writing config={{ apiKey }} inline does not rebuild it on every render.

config also takes getPath, and the links between entries inside the bodies the hooks return then get their href:

tsx
<KookeeProvider config={{ apiKey: import.meta.env.VITE_KOOKEE_API_KEY, getPath }} locale="en">

getPath takes an entry (its type, id, slug, locale and category) and returns its path on your site, or null when the entry has no page there. Without it those links have no href and read as text. An inline getPath does not rebuild the client either: the provider keeps the latest one, so the hooks do not refetch. It needs @kookee/react 1.17.0 with @kookee/sdk 1.17.0.

A hook used outside the provider throws Kookee hooks must be used within a <KookeeProvider>, so a missing provider fails loudly instead of silently returning nothing.

apiKey or projectId

Use your project's API key. It is built to ship in browser code: it reads published content, and its only writes are reactions, chat messages, consent records and the private messages visitors send from the site widget's Feedback tab. Restrict it to your domains with the project's allowed origins. See API keys and security.

tsx
<KookeeProvider config={{ apiKey: import.meta.env.VITE_KOOKEE_API_KEY }}>

While the project's hosted portal is enabled, projectId works in place of the key. Without the portal, the API refuses requests that carry only a project id, with 403 PORTAL_NOT_ENABLED.

tsx
<KookeeProvider config={{ projectId: 'your-project-id' }}>

What a hook returns

Three shapes, depending on what the endpoint returns.

Paginated lists — useBlogPosts, useHelpArticles, useEntries, useComments and friends:

tsx
const {
  data,          // T[] — every page loaded so far, flattened
  isLoading,     // the first page is in flight
  isLoadingMore, // a loadMore() page is in flight
  error,         // unknown; null when fine
  hasMore,       // another page exists
  total,         // how many rows match, server-side
  loadMore,      // () => void
  refetch,       // () => void
} = useBlogPosts({ limit: 10 });

A single entry — every useXxx(slug) and useXxxById(id) hook:

tsx
const { data, isLoading, error, refetch } = useBlogPost(slug);
// data is null until the request lands

A bare array — categories, tags, search results, feedback columns, config lists:

tsx
const { data, isLoading, error, refetch } = useHelpCategories();
// data is [] while loading, never null, so you can map it straight away

That difference matters in practice: data.map(...) is safe from the first render on a list or array hook, and needs a guard on a single-entry one.

useReact is the exception to all three — it is a mutation, covered below.

The hooks

Module

Hooks

Blog

useBlogPosts · useBlogPost · useBlogPostById · useBlogTags

Pages

usePages · usePage · usePageById

Help

useHelpArticles · useHelpArticle · useHelpArticleById · useHelpCategories · useHelpSearch

Changelog

useChangelog · useChangelogEntry · useChangelogEntryById

Announcements

useAnnouncements · useAnnouncement

FAQ

useFaq · useFaqCategories

Feedback

useFeedbackPosts · useFeedbackPost · useFeedbackColumns · useFeedbackTopContributors · useFeedbackComments

Status

useStatus · useStatusIncident

Any type

useEntries · useEntry · useEntryById · useEntryTags · useEntryCategories

Shared

useComments · useReact · useConfig · useConfigList · useTranslations · useTranslationsById

All of them come from the package root:

tsx
import { useBlogPosts, useHelpSearch, useReact, useKookee } from '@kookee/react';

Two things that catch people out. Announcements are addressed by id only — there is no slug lookup for them, which is why the list is useAnnouncement and not useAnnouncementBySlug. And feedback is not localized: useFeedbackPosts, useFeedbackPost and useFeedbackComments deliberately ignore the provider's locale, because their endpoints do not accept one.

Filtering and paginating a list

List hooks take the module's parameters as the first argument, and refetch from page one whenever those change:

tsx
function Blog({ tag }: { tag?: string }) {
  const { data, isLoading, total, hasMore, isLoadingMore, loadMore } = useBlogPosts({
    limit: 10,
    tags: tag ? [tag] : undefined,
  });

  if (isLoading) return <Spinner />;

  return (
    <>
      <p>{total} posts</p>
      {data.map((post) => (
        <article key={post.id}>{post.title}</article>
      ))}
      {hasMore && (
        <button onClick={loadMore} disabled={isLoadingMore}>
          {isLoadingMore ? 'Loading…' : 'Load more'}
        </button>
      )}
    </>
  );
}

loadMore() appends the next page to data. It does nothing when hasMore is false or a page is already in flight, so a double click cannot fetch the same page twice and you do not need a guard of your own.

refetch() re-runs the current query from page one — use it after a mutation elsewhere in your app:

tsx
const { data, refetch } = useFeedbackPosts({ limit: 20 });
// after the visitor posts on your feedback portal
await refetch();

Detail hooks stay idle until their argument resolves

Pass undefined and the hook makes no request at all: isLoading is false, data is null, nothing is fetched.

tsx
const { slug } = useParams();
const { data: post, isLoading } = useBlogPost(slug); // idle while slug is undefined

This is what makes router params safe. A hook that fired on undefined would either request /blog/undefined or force a guard into every component; here the idle state is the default, and the request starts by itself the moment the param arrives. You never need a conditional hook call, which React does not allow anyway.

Everything that takes an id or a slug behaves this way — useHelpArticle, useEntryById, useComments, useConfig, useTranslations and the rest:

tsx
// The comment list stays idle until the article it belongs to has loaded.
const { data: article } = useHelpArticle(slug);
const { data: comments } = useComments(article?.id);

The generic entry hooks

The generic entry hooks read any built-in type by its slug: blog, page, help_article, changelog, announcement or faq. type is required:

tsx
const { data: releases } = useEntries({ type: 'changelog', limit: 20 });
const { data: release } = useEntry(slug, { type: 'changelog' });
const { data: byId } = useEntryById(id); // no type needed — an id is unambiguous

Their tags and categories have their own hooks, both keyed by type:

tsx
const { data: tags } = useEntryTags('blog');
const { data: categories } = useEntryCategories('help_article');

useEntries also takes category, tags, search and filter, the last one keyed by field slug:

tsx
const { data } = useEntries({
  type: 'changelog',
  search: 'export',
  filter: { changelogType: 'fix' },
  limit: 12,
});

useHelpSearch debounces the query internally, so wire it straight to the input — do not debounce it again. A second debounce only stacks delay on top of the one already there.

tsx
function Search() {
  const [query, setQuery] = useState('');
  const { data: results, isLoading } = useHelpSearch(query);

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search help" />
      {isLoading && <Spinner />}
      {results.map((result) => (
        <a key={result.id} href={`/help/${result.slug}`}>
          <strong>{result.title}</strong>
          {result.matchedChunk && <span>{result.matchedChunk}</span>}
        </a>
      ))}
    </>
  );
}

The hook stays idle while the debounced query is empty, so an empty box makes no requests at all. Each result is a help article summary plus matchedChunk — the passage that matched, ready to use as the snippet under the title.

A second argument takes limit and locale options:

tsx
const { data } = useHelpSearch(query, { limit: 5 });

See Building a help center with search and AI chat for putting this next to the AI answer.

FAQ

useFaq reads the FAQ items of one category, and each item carries its answer, so one request fills a section. category is the slug in your project's default language:

tsx
const { data: items } = useFaq({ category: 'pricing', limit: 50 });

useFaqCategories() returns the categories as a bare array, for a page with one section per category. Both need @kookee/react 1.21.0 with @kookee/sdk 1.21.0. Add a FAQ to your site renders the items with a ready-made component.

Status

useStatus reads your project's status page: its indicator, its components with their 90-day uptime, the open incidents and maintenance, and the incidents of the last 90 days. useStatusIncident(id) reads one published incident or maintenance with all its updates, and stays idle while id is undefined. Neither takes a locale, because incidents are written in one language.

tsx
const { data: status } = useStatus({ refreshSeconds: 60 });

status?.indicator; // 'operational' | 'minor' | 'major' | 'maintenance'
status?.activeIncidents; // open incidents, newest first, each with its latest update

refreshSeconds refetches that often while the tab is visible, and once more when a hidden tab is shown again after that long, so an open status page stays current. Every hook except the paginated lists and useReact takes it. The interval is 30 seconds at the least. A 429 doubles the wait, up to 10 minutes, and a 401 or 403 stops it. A refetch that fails keeps the data it had, with error set.

Status reads do not count against the monthly API quota. useStatusIncident and refreshSeconds need @kookee/react 1.19.0 with @kookee/sdk 1.19.0. Show your status page on your own site renders both with ready-made components.

Reactions

useReact is the one mutation in the package. It fires only when you call it, and returns react, isPending and error rather than the usual query shape:

tsx
import { useReact } from '@kookee/react';
import type { BlogEntryDetail } from '@kookee/sdk';

function ReactButton({ post }: { post: BlogEntryDetail }) {
  const [reactions, setReactions] = useState(post.reactions);
  const { react, isPending, error } = useReact(post.id);

  return (
    <>
      <button
        disabled={isPending}
        onClick={async () => {
          const result = await react({ reactionType: 'heart', action: 'add' });
          setReactions(result.reactions);
        }}
      >
        {isPending ? '…' : `Heart ${reactions.heart ?? 0}`}
      </button>
      {error && <p>Could not save that.</p>}
    </>
  );
}

isPending is true for the duration of the call — use it to disable the button so a fast double click cannot send two. react() resolves with the updated reactions map and also rejects on failure, so you can either await it inside a try or read error.

It does not update the entry in place. The hook holding that post keeps its old counts until you use the returned map, as above, or call that hook's refetch(). See Reactions, views and engagement data.

For reaction buttons that remember what the visitor pressed, update their counts the moment they are clicked and need no provider, use Reactions from @kookee/react/entry/client instead; see Build a blog with the React components.

Rendering an entry's body

Detail responses carry contentHtml. EntryContent renders it:

tsx
import { EntryContent } from '@kookee/react';

function Post({ slug }: { slug: string | undefined }) {
  const { data: post } = useBlogPost(slug);
  if (!post) return null;

  return <EntryContent entry={post} className="prose" as="article" />;
}
  • entry — a detail entry. List responses have no contentHtml, so passing a list item is a compile error rather than a blank page.

  • className — merged after the always-present kookee-entry-content class.

  • as — which element to render. Defaults to div.

It has no effects and reads nothing from the browser, so it produces the same markup on the server and the client.

In a React Server Component, import it from @kookee/react/entry rather than the package root. The root is a client module, so Next.js would render EntryContent as a client component and send the body to the browser a second time, inside its props. Either import keeps the body's DOM intact when the parent re-renders, which an inline dangerouslySetInnerHTML={{ __html }} does not do in React 19.

For syntax-highlighted code blocks and file attachment chips, import the SDK's content stylesheet — it is scoped to the kookee-entry-content class the component always sets:

tsx
import '@kookee/sdk/styles/content.css';

That is the stylesheet for entry content. There is no code.css. In a Tailwind v4 app, import it into a cascade layer instead, so your prose-code: utilities keep winning over its defaults:

CSS
@import '@kookee/sdk/styles/content.css' layer(components);

If your app has no typography system of its own, add @kookee/sdk/styles/typography.css as well, for baseline headings, lists, tables and images.

The chat widget's stylesheet is a separate import from a different package and has nothing to do with entry content — do not reach for one when you meant the other:

tsx
import { KookeeChatWidget } from '@kookee/react/chat';
import '@kookee/react/chat.css';

Rendering content and styling code blocks covers theming those styles and the Tailwind caveats in full.

Reading custom fields

A changelog's type and version, and every field you defined yourself, live in entry.fields — not as top-level properties. Read them with the SDK's helpers rather than searching the array by hand:

tsx
import { fieldOptionKey, fieldStringValue } from '@kookee/sdk';

function Release({ slug }: { slug: string | undefined }) {
  const { data: release } = useChangelogEntry(slug);

  const type = fieldOptionKey(release?.fields, 'changelogType'); // 'feature' | 'fix' | …
  const version = fieldStringValue(release?.fields, 'version'); // '2.1.0'

  return (
    <header>
      {type && <span className={`badge badge-${type}`}>{type}</span>}
      {version && <code>{version}</code>}
    </header>
  );
}

fieldOptionKey gives you the select option's stable key, which survives label edits and translation — key your badges and branches off that, never off the visible label. fieldStringValue gives you text values. Both return undefined when the field is absent or empty, so entry types that do not have the field need no special-casing.

The client itself

useKookee() hands you the underlying SDK client — the escape hatch for anything the hooks do not cover, and the starting point for imperative calls in event handlers:

tsx
import { useKookee } from '@kookee/react';

function ExportButton() {
  const kookee = useKookee();

  const onExport = async () => {
    const page = await kookee.blog.list({ limit: 100 });
    downloadJson(page.data);
  };

  return <button onClick={onExport}>Export posts</button>;
}

It is the same client instance every hook uses, so it already carries the provider's apiKey, projectId, baseUrl and getPath.

Types

Every type comes from @kookee/sdk, not from the React package:

tsx
import type { BlogEntryListItem, BlogEntryDetail, HelpSearchResult, PaginatedResponse } from '@kookee/sdk';

Next

Server rendering and the generic React hooks covers initialData for framework loaders, what it means that these hooks do no caching of their own, and the three generic hooks the named ones are built from.

React components for your blog, changelog and help center covers the ready-made components: lists, articles, filters, pagination, a table of contents, reactions and search.

Cet article vous a-t-il aidé ?