Can you help me create a custom React hook called useFormValidator for a trading form that needs to be super fast? I want it to use Zod for validation but run the validation in a Web Worker so it doesn't block the UI when users are typing quickly.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing React hook with worker-based Zod validation
Creating a custom React hook that offloads form validation to a web worker using Zod ensures non-blocking, fast UI updates; the hook posts form data to the worker, which runs the Zod schema and returns validation results asynchronously. The example includes a Zod schema, a worker script that validates incoming data, and a React hook managing the worker lifecycle and results, with optional debouncing to limit validation frequency.
Below is a simple pattern for a “super fast” Zod-based validator that runs in a Web Worker so it doesn’t block typing. The idea is:
Create a worker that imports your Zod schema and validates data sent from the main thread.
Use a custom hook to post form values to the worker and listen for validation results.
(Optional) Add debouncing if you want to cut down on worker messages for very frequent keystrokes.
This example uses TypeScript, but you can adapt it to plain JS.
1) Define your Zod schema
src/validation/tradeSchema.ts (just an example)
ts
import { z } from 'zod';
export const tradeSchema = z.object({
symbol: z.string().min(1, 'Symbol is required'),
side: z.enum(['BUY', 'SELL']),
quantity: z
.number()
.positive('Quantity must be greater than zero')
.max(10_000, 'Max quantity is 10,000'),
price: z
.number()
.positive('Price must be greater than zero')
.max(1_000_000, 'Price too high'),
});
export type TradeFormData = z.infer<typeof tradeSchema>;
2) Create the Web Worker
src/workers/formValidatorWorker.ts (Depending on your bundler, you might use new URL('./formValidatorWorker.ts', import.meta.url) in your hook.)
ts
/// <reference lib="webworker" />
import { tradeSchema } from '../validation/tradeSchema';
export type ValidationRequest = {
id: number; // some request ID to match responses
data: unknown; // incoming form data
};
export type ValidationResponse = {
id: number;
success: boolean;
errors?: Record<string, string>;
};
self.onmessage = (event: MessageEvent<ValidationRequest>) => {
const { id, data } = event.data;
try {
// Will throw if invalid
tradeSchema.parse(data);
const response: ValidationResponse = {
id,
success: true,
};
(self as unknown as Worker).postMessage(response);
} catch (err: any) {
const zodErrors: Record<string, string> = {};
if (err?.errors) {
// Zod error format
for (const e of err.errors) {
if (e.path && e.path.length) {
zodErrors[e.path.join('.')] = e.message;
}
}
}
const response: ValidationResponse = {
id,
success: false,
errors: zodErrors,
};
(self as unknown as Worker).postMessage(response);
}
};
3) Create the useFormValidator Hook
src/hooks/useFormValidator.ts
ts
import { useEffect, useRef, useState } from 'react';
import type { ValidationResponse } from '../workers/formValidatorWorker';
// If you’re using Vite or CRA with supported setup:
const workerUrl = new URL('../workers/formValidatorWorker.ts', import.meta.url);
type UseFormValidatorOptions = {
debounceMs?: number;
};
export function useFormValidator<FormData = any>(
initialData: FormData,
options: UseFormValidatorOptions = {}
) {
const { debounceMs = 0 } = options;
const workerRef = useRef<Worker | null>(null);
const [data, setData] = useState<FormData>(initialData);
const [errors, setErrors] = useState<Record<string, string>>({});
const [validating, setValidating] = useState(false);
// Incremental ID to match responses
const requestIdRef = useRef(0);
// Keep track of the last request ID we sent
const pendingIdRef = useRef<number | null>(null);
useEffect(() => {
// Create the worker
workerRef.current = new Worker(workerUrl, { type: 'module' });
// Listen for messages
workerRef.current.onmessage = (event: MessageEvent<ValidationResponse>) => {
const { id, success, errors: workerErrors } = event.data;
// Only handle if it matches our pending ID
if (pendingIdRef.current === id) {
setValidating(false);
setErrors(workerErrors || {});
pendingIdRef.current = null;
}
};
return () => {
workerRef.current?.terminate();
workerRef.current = null;
};
}, []);
// Helper to send data to worker
const sendToWorker = (nextData: FormData) => {
if (!workerRef.current) return;
const nextId = ++requestIdRef.current;
pendingIdRef.current = nextId;
setValidating(true);
workerRef.current.postMessage({ id: nextId, data: nextData });
};
// Debounce logic (if desired)
useEffect(() => {
if (debounceMs > 0) {
const handle = setTimeout(() => {
sendToWorker(data);
}, debounceMs);
return () => clearTimeout(handle);
} else {
sendToWorker(data);
}
}, [data, debounceMs]);
// Update form data
const updateField = <K extends keyof FormData>(key: K, value: FormData[K]) => {
setData(prev => ({ ...prev, [key]: value }));
};
return {
data,
setData,
updateField,
errors,
validating,
};
}
If you’re using Create React App, you may need a custom react-app-rewired setup or use something like workerize-loader to import the worker. With Vite, the new URL('./formValidatorWorker.ts', import.meta.url) approach usually works out of the box.
This pattern is flexible: you can add more schemas, more fields, or switch the schema at runtime.
Debouncing is optional; if you want immediate validation on every keystroke, just set debounceMs to 0.
For performance, keep the worker lean—only import what’s necessary. If you have a large set of schemas, consider code splitting or dynamic imports in the worker.
With this setup, your fast-typing traders won’t see UI lag from validation—everything is offloaded to the worker.