useReducer
If a component keeps a union of states in useReducer, declare the reducer as a machine with kotick/reducer. kotick then lists every state of it and previews any state in place.
An app that uses only kotick/reducer does not need xstate or @xstate/react. Install kotick alone.
Quick start
- Declare the reducer as a machine with
defineReducerMachine. From a switch reducer gives the steps. - In the component, call
useMachineReducer(machine, initial)in place ofuseReducer(reducer, initial). - Mount
<Kotick />once, as Installation shows. - Use the app until the component is in a second state. The panel lists every state, and an R mark shows each state that you visited.
- Select a visited state in the panel. The component shows that state in place, with the data of your visit.
A state that you did not visit is greyed out until it has a fixture. To start the fixtures file, select a visited state and use Copy context. The JSON is the fixture of that state. For a state that is difficult to get to in the app, write the object by hand. Previews gives the rule.
From a switch reducer
A switch reducer has one branch for each event. A machine has one handler for each state and event.
- Make the state a union with one key that holds the name of the state. That key is the
discriminant. - For each branch of the
switch, write a handler under each state in which the event is valid. Leave it out of the other states, and they ignore the event. - Move each
useEffectthat depends on the name of the state to theeffectof that state. Changedispatchtosend, and read props and hook values throughinput(). - Change
useReducer(reducer, initial)touseMachineReducer(machine, initial). - Keep the tests of the old reducer, and run them on
machine.reducer.
This reducer of a search box accepts SEARCH while it is not loading, and RESOLVE and CANCEL only while it is loading:
As a machine, each state lists the events that it accepts. The search request, which a useEffect in the component started, is the effect of loading:
Define a machine
A machine has five rules. The types check rules 1 and 3, and each fixture of rule 2. The panel shows each state that has no data. Rules 4 and 5 are yours to follow.
- One key, the
discriminant, holds the name of the state.stateshas one entry for each name. TypeScript checks the entries against your union, so a missing state, an extra state and a misspelled event do not compile. - A state needs data before it can preview. A visit in the app records its state object, and
defineFixturestakes a state object for each state that you list. A fixture is a whole state of its own name. To make the file fail when a state has no fixture, check the set withsatisfies CompleteFixtures<typeof machine>. Refer to Fixtures. - Transitions are per state and per event. A handler gets the state object of its state and the event of its type, and returns the next state. A state ignores the events that it does not list, and a handler that returns
stateignores its event. A handler gets no input, because it must be pure, as a reducer is.machine.reduceris the plain reducer, for unit tests. - Effects are per state. An
effectstarts after the commit that enters its state. Its cleanup runs after the commit that leaves the state, and when the component unmounts. A transition that keeps the name of the state keeps the effect running. A batch of events that leaves the state and enters it again also runs the cleanup and starts the effect again. After the cleanup, itssenddoes nothing. React's rules for effects apply, so StrictMode starts the effect, runs its cleanup and starts it again when the component mounts. An effect gets(state, send, input).input()returns the newest input that the component gave the hook, so an effect can call the router, a client from React context or a callback prop. - Async work is in the machine. Start a request in the
effectof a state, and give its result tosend. During a preview, kotick blocks each event that the component dispatches, and it does not replay the events after the release. So a click handler that doesdispatch({ type: 'SUBMIT' }), thenawait submitOrder(), thendispatch({ type: 'RESOLVE' })losesRESOLVEif a preview is open when the response comes. After the release, the real state isloading, and it stays inloading. A componentuseEffectthat sends the result has the same problem, and it also runs for a previewed state. kotick never blocks thesendof a machine effect, and a previewed state runs no machine effect.
Use the machine
useMachineReducer(machine, initial, options?) returns [state, dispatch], as useReducer does. initial is the first state, or a function that returns it.
options.input is the value that input() returns in the effects. Declare its type as the third type argument of defineReducerMachine, and the hook then requires it. For searchMachine, an input without onHits does not compile. The object is new on each render, but the search does not restart, because the effect reads the input through input() when it needs it. A new input never restarts an effect.
RESOLVE comes from send, so a preview that is open when the response comes does not block it. The real state goes to ready, and the release shows it.
options.debug takes { label, disabled }. label is the name of the instance in the panel, and disabled: true keeps the instance out of kotick. kotick reads debug in development builds only.
Each component that calls the hook is one instance. Do not give machine.reducer to useReducer in a component. The state then changes, but no effect runs, and the panel does not list the component.
Previews
The rules in Previews apply. When you select a state, the component gets a state object of that state in place of the real one. It does not mount again.
The state object comes from a recording or a fixture of the selected state. The live state object fits only the state that the machine is in, so Live is available only for that state. Thus, you cannot preview another state that has no recording and no fixture yet. The panel greys it out and names it under States.
During a preview, the panel logs the events that the component dispatches, and they do not get to the machine. The effect of the real state continues to run. When you release the preview, the component shows the real state at that time.
kotick checks only the name of the state. A recording from before you added a field to a state does not have that field.
Production builds
Production builds keep defineReducerMachine and useMachineReducer as a small runtime around React's useReducer and useEffect. The runtime runs your transitions and effects. The registry, the panel, the recordings and the fixtures are removed. defineFixtures stays only if production code imports it. Refer to Choose an adapter for the size of the runtime.
- A server component or a route handler can import a machine file and call
machine.reducer. OnlyuseMachineReduceris client code. - The runtime calls only built-in functions that every browser that runs React has, such as
Object.freezeandObject.is. Its code uses ES2020 syntax, so a build for an older browser must transpilekotick.
The rules are public API
The rules above are public API. A change to a rule, to the arguments of a handler or an effect, or to the order of start and cleanup is a breaking change. While kotick is 0.x, a breaking change bumps the minor version, and never a patch.
Remove kotick
To remove kotick, write a reducer that picks the handler by the name of the state and the type of the event, and a useEffect that runs the effect of the state. The handlers and the effects are plain functions, so they move as they are.
How the adapter works
The adapter keeps the state in React. useMachineReducer runs the reducer of the machine in React's useReducer, and runs the effect of the real state. In development, it also registers the instance, records its state object after each commit, and returns the state object of a preview in place of the real one.
A preview changes only the state object that the hook returns. The real state stays in useReducer, and its effect continues to run. During a preview, dispatch logs each event in the panel, and the event does not get to the machine. The send of a machine effect goes to the real machine, also during a preview.