Skip to content

useMachine

Read as Markdown

useMachine(definition, { input }) from @pibbl/core/machines creates one stable actor per hook slot. It starts after a successful mounting render and stops on unmount. An abandoned mounting render starts no tasks. Input and definition are captured at initial mount; later input objects do not restart the actor.

Send events from handlers or owned work. Read actor.snapshot.get() in a component, or select a field with useComputed. The initial render can observe not-started; entry effects and tasks start only after the render succeeds.

import { Text } from "@pibbl/core";
import { defineMachine, useMachine } from "@pibbl/core/machines";
const menu = defineMachine<undefined, { type: "TOGGLE" }>({
initial: "closed",
context: () => undefined,
states: {
closed: { on: { TOGGLE: "open" } },
open: { on: { TOGGLE: "closed" } },
},
});
function Menu() {
const actor = useMachine(menu, { input: undefined });
return (
<Text onClick={() => actor.send({ type: "TOGGLE" })}>
{actor.snapshot.get().value}
</Text>
);
}

See machine authoring and machine types.

Related types: MachineDefinition, MachineActor, CreateMachineOptions.

Creates one component-owned state-machine actor for a hook slot.

The actor starts only after its mounting render commits successfully and stops when the component unmounts. Its input is captured on the initial mount; changing an input object on a later render does not recreate or restart the actor. Use machine events for application state changes.

useMachine: <Context, Event extends MachineEvent, Input, State extends string>(definition: MachineDefinition<Context, Event, Input, State>, options: { readonly input: Input; }) => MachineActor<Context, Event, Input, State>

Related API: useMachine, MachineEvent, MachineDefinition, MachineActor.

  • Context — Immutable machine context carried by each snapshot.

  • Event — Events accepted by the machine actor.

  • Input — Immutable input captured when this hook slot mounts.

  • definition — Immutable machine behavior shared by all actor instances.

  • options — Input used to initialize this mounted actor.

A stable actor with a readonly reactive snapshot.

const actor = useMachine(menuMachine, { input: { initialOpen: false } });
const open = () => actor.send({ type: 'OPEN' });
return <Text>{actor.snapshot.get().value}</Text>;

createMachine

MachineActor

View source — packages/core/src/features/machines/hook.ts:52

Read the Authoring, signals, and lifecycle companion for ownership, adaptation, failure modes, and verification. Agent start provides the version-selection workflow.

Documentation built with @pibbl/core 0.0.2, revision 272a94a. ALPHA — NOT FOR PRODUCTION USE.