React

Zero has built-in support for React. Here’s what basic usage looks like:

import {useQuery, useZero} from '@rocicorp/zero/react';
import {type Schema} from './schema.ts';
import {type Mutators} from './mutators.ts';

function IssueList() {
  const z = useZero<Schema, Mutators>();
  let issueQuery = z.query.issue
    .related('creator')
    .related('labels')
    .limit(100);

  const userID = selectedUserID();

  if (userID) {
    issueQuery = issueQuery.where('creatorID', '=', userID);
  }

  const [issues, issuesDetail] = useQuery(issueQuery);

  return (
    <>
      <div>
        {issuesDetail.type === 'complete' ? 'Complete' : 'Partial'}
        results
      </div>
      <div>
        {issues.map(issue => (
          <IssueRow issue={issue} />
        ))}
      </div>
    </>
  );
}

ZeroProvider

The useZero hook must be used within a ZeroProvider component. The ZeroProvider component is responsible for providing the context to your components.

import {ZeroProvider} from '@rocicorp/zero/react';

export function Root() {
  const zero = new Zero<Schema, Mutators>(...);
  return (
    <ZeroProvider zero={zero}>
      <App />
    </ZeroProvider>
  );
}

createUseZero

It is often inconvenient to provide the type parameters to useZero repeatedly. To simplify this, we provide a function that creates a hook with the types you want.

import {createUseZero} from '@rocicorp/zero/react';
import type {Schema} from './schema.ts';
import type {Mutators} from './mutators.ts';

export const useZero = createUseZero<Schema, Mutators>();

You can then import this useZero hook in your components and use it without having to specify the type parameters.

import {useQuery} from "@rocicorp/zero/react";
import {useZero} from './hooks/use-zero.ts';

function IssueList() {
  const z = useZero();
  ...
}

Complete quickstart here:

https://github.com/rocicorp/hello-zero