React / foldkit-react

Foldkit inside React

Embed a Foldkit Runtime.makeElement program with Ports inside any React component using FoldkitComponent.define (assuming makeCounter and makeDashboard return Runtime.makeElement programs with matching inbound/outbound Ports):

ts
import { FoldkitComponent } from 'foldkit-react'

const Counter = FoldkitComponent.define({
  make: (container, props: CounterProps) => makeCounter(container, props.initialCount),
  inbound: { stepChanged: props => props.step },
  outbound: { countChanged: (count, props) => props.onCountChange?.(count) },
})

// Usage in JSX: <Counter initialCount={10} step={2} onCountChange={setCount} />

make runs once per mounted runtime; inbound selects prop slices to push into inbound Ports whenever Object.is changes; outbound invokes the latest prop callback without resubscribing. Bindings validate against each Port's encoded Schema type.

FoldkitComponent renders a <div> (accepting className and style) and embeds Foldkit inside a child container React leaves alone, buffering early inbound/outbound values across startup, handling React Strict Mode double-mounts cleanly, logging invalid inbound values without re-sending them on every render, and disposing Subscriptions and Commands on unmount.

Customize equality and restart keys

ts
const Dashboard = FoldkitComponent.define({
  make: (container, props: DashboardProps) => makeDashboard(container, props.userId),
  inbound: { filtersChanged: { select: props => props.filters, equals: shallowEqual } },
  restartKey: props => props.userId,
})

When restartKey changes (Object.is), the previous Foldkit runtime disposes and a fresh runtime starts with current props and inbound values.

Use useFoldkitElement for direct Port handles

ts
import { useFoldkitElement } from 'foldkit-react'
import { createElement, useEffect } from 'react'

const HookCounter = ({ step }: { readonly step: number }) => {
  const { ref, handle } = useFoldkitElement({
    make: container => makeCounter(container, 0),
  })
  useEffect(() => {
    handle?.ports.stepChanged.send(step)
  }, [handle, step])
  return createElement('div', { ref })
}

handle is undefined before mount and after unmount; pass onEmbed to subscribe immediately after embed before init Commands emit. Keep the ref element free of React children.

Limits

  • React children only inside islands: Pass React elements via props.children and place Foldkit markup alongside the island.
  • No cross-framework Suspense: Outer React <Suspense> boundaries wait on React resources, while embedded Foldkit programs render loading states from their own Model.
  • Client-rendered islands: Server rendering emits an empty <foldkit-react-host>; the React island mounts on the client.
  • Overloaded event callbacks: Event argument types infer from the last overload of an overloaded callback prop.

Next