javascript / expert
Snippet
Orchestrating Complex Control Flow with Generator Functions in Custom React Hooks
ES6 Generator functions allow fine-grained state machine orchestration in React components. By keeping iterator instances in a React useRef and stepping through yield points with state dispatching, multi-step asynchronous workflows can be controlled deterministically and tested isolate from React render loops.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { useState, useCallback, useRef } from 'react';type StepGenerator = Generator<string, void, unknown>;export function useWorkflow(workflowFn: () => StepGenerator) {const generatorRef = useRef<StepGenerator | null>(null);const [currentStep, setCurrentStep] = useState<string | null>(null);const start = useCallback(() => {generatorRef.current = workflowFn();const first = generatorRef.current.next();setCurrentStep(first.done ? null : first.value);}, [workflowFn]);const advance = useCallback((payload?: unknown) => {if (!generatorRef.current) return;const res = generatorRef.current.next(payload);setCurrentStep(res.done ? null : res.value);}, []);return { currentStep, start, advance };}
react
Breakdown
1
type StepGenerator = Generator<string, void, unknown>;
Defines the TypeScript type contract for step-yielding state generators.
2
generatorRef.current = workflowFn();
Persists the generator iterator instance across React re-renders using useRef to avoid re-instantiation.
3
const res = generatorRef.current.next(payload);
Resumes execution of the workflow until the next yield statement, optionally injecting state payload.