Formbit is a lightweight React state form library designed to simplify form management within your applications. With Formbit, you can easily handle form state, validate user input, and submit data efficiently.
- Intuitive and easy-to-use form state management.
- Out of the box support for validation with yup.
- Full TypeScript generics —
useFormbit<FormData>(...)infers paths, values, and callbacks. - Support for handling complex forms with dynamic and nested fields via dot-path notation.
- Context Provider for sharing form state across deeply nested component trees.
- Seamless and flexible integration with React — works with Antd, MaterialUI, or plain HTML.
yup, lodash and react are peer dependencies: install them alongside formbit.
npm install @radicalbit/formbit yup lodashyarn add @radicalbit/formbit yup lodashThe hook is exported both as the default export and as the named export useFormbit. Bundlers (Vite, webpack, …) handle either. In plain Node ESM, or with TypeScript moduleResolution: node16/nodenext, use the named one:
import { useFormbit } from '@radicalbit/formbit';Three steps: define a schema, call the hook, bind the UI.
import * as yup from 'yup';
import useFormbit from '@radicalbit/formbit';
// 1. Define a Yup schema and infer the TypeScript type from it
const schema = yup.object({
name: yup.string().max(25, 'Max 25 characters').required('Name is required'),
age: yup.number().max(120, 'Must be 0–120').required('Age is required'),
});
type FormData = yup.InferType<typeof schema>;
const initialValues: Partial<FormData> = { name: undefined, age: undefined };
// 2. Call the hook with generics so every callback is fully typed
function Example() {
const { form, submitForm, write, error, isDirty } = useFormbit<FormData>({
initialValues,
yup: schema,
});
const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('name', value);
};
const handleChangeAge = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('age', Number(value));
};
const handleSubmit = () => {
submitForm(
({ form }) => console.log('Validated form:', form),
({ errors }) => console.error('Validation errors:', errors),
);
};
// 3. Bind inputs, errors, and submit — Formbit stays out of your UI
return (
<div>
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
value={form.name ?? ''}
onChange={handleChangeName}
/>
<div>{error('name')}</div>
<label htmlFor="age">Age</label>
<input
id="age"
type="number"
value={form.age ?? ''}
onChange={handleChangeAge}
/>
<div>{error('age')}</div>
<button disabled={!isDirty} onClick={handleSubmit} type="button">
Submit
</button>
</div>
);
}
export default Example;Use FormbitContextProvider when you need to share form state across deeply nested components without prop drilling.
import { FormbitContextProvider, useFormbitContext } from '@radicalbit/formbit';
import * as yup from 'yup';
const schema = yup.object({
name: yup.string().required('Name is required'),
surname: yup.string().required('Surname is required'),
age: yup.number().required('Age is required'),
});
type FormData = yup.InferType<typeof schema>;
const initialValues: Partial<FormData> = { name: undefined, surname: undefined, age: undefined };
// Wrap your form tree with the provider
function App() {
return (
<FormbitContextProvider<FormData>
initialValues={initialValues}
yup={schema}
>
<NameField />
<SubmitButton />
</FormbitContextProvider>
);
}
// Any child can access form state without props
function NameField() {
const { form, write, error } = useFormbitContext<FormData>();
const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('name', value);
};
return (
<div>
<input
value={form.name ?? ''}
onChange={handleChangeName}
/>
<span>{error('name')}</span>
</div>
);
}
function SubmitButton() {
const { submitForm, isDirty } = useFormbitContext<FormData>();
return (
<button
disabled={!isDirty}
onClick={() => submitForm(({ form }) => console.log(form))}
>
Submit
</button>
);
}Start with empty initial values and call initialize() once data arrives from an API.
import { useEffect, useState } from 'react';
import useFormbit from '@radicalbit/formbit';
import * as yup from 'yup';
const schema = yup.object({
name: yup.string().required(),
email: yup.string().email().required(),
});
type FormData = yup.InferType<typeof schema>;
const initialValues: Partial<FormData> = { name: undefined, email: undefined };
function EditUserForm({ userId }: { userId: string }) {
const { form, write, error, initialize, submitForm } = useFormbit<FormData>({
initialValues,
yup: schema,
});
const [loading, setLoading] = useState(true);
// Fetch and initialize — resetForm() will revert to these values
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((user) => { initialize(user); setLoading(false); });
}, [userId]);
const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('name', value);
};
const handleChangeEmail = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('email', value);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
submitForm(({ form }) => console.log(form));
};
if (loading) return <p>Loading...</p>;
return (
<form onSubmit={handleSubmit}>
<input value={form.name ?? ''} onChange={handleChangeName} />
<div>{error('name')}</div>
<input value={form.email ?? ''} onChange={handleChangeEmail} />
<div>{error('email')}</div>
<button type="submit">Save</button>
</form>
);
}Use __metadata to store step state and validateAll to gate navigation between steps.
import useFormbit from '@radicalbit/formbit';
import * as yup from 'yup';
const schema = yup.object({
name: yup.string().required('Name is required'),
age: yup.number().required('Age is required'),
email: yup.string().email().required('Email is required'),
});
type FormData = yup.InferType<typeof schema>;
const initialValues: Partial<FormData> & { __metadata: { step: number } } = {
name: undefined,
age: undefined,
email: undefined,
__metadata: { step: 0 },
};
function MultiStepForm() {
const { form, write, error, validateAll, submitForm } = useFormbit<FormData>({
initialValues,
yup: schema,
});
const step = (form.__metadata?.step as number) ?? 0;
const goTo = (n: number) => write('__metadata.step', n);
// Validate only the current step's fields before advancing
const next = (paths: string[]) => {
validateAll(paths, {
successCallback: () => goTo(step + 1),
});
};
const handleChangeName = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('name', value);
};
const handleChangeAge = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('age', Number(value));
};
const handleChangeEmail = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
write('email', value);
};
const handleSubmit = () => {
submitForm(({ form }) => console.log('Submit:', form));
};
return (
<div>
{step === 0 && (
<div>
<input value={form.name ?? ''} onChange={handleChangeName} />
<div>{error('name')}</div>
<button onClick={() => next(['name'])}>Next</button>
</div>
)}
{step === 1 && (
<div>
<input type="number" value={form.age ?? ''} onChange={handleChangeAge} />
<div>{error('age')}</div>
<button onClick={() => goTo(0)}>Back</button>
<button onClick={() => next(['age'])}>Next</button>
</div>
)}
{step === 2 && (
<div>
<input value={form.email ?? ''} onChange={handleChangeEmail} />
<div>{error('email')}</div>
<button onClick={() => goTo(1)}>Back</button>
<button onClick={handleSubmit}>Submit</button>
</div>
)}
</div>
);
}Errors that do not come from the yup schema — typically a message returned by your backend — can be stored under the reserved silent key of errors. A silent error:
- is written with
setError('silent', message)and read witherror('silent'); - never goes through yup validation;
- is ignored by
isFormValid()andisFormInvalid(), so it does not disable your submit button; - survives
write,validateand live validation of other fields; - is cleared by
validateForm,submitForm(whether the form is valid or not),resetFormandinitialize, so every new submit starts clean.
Nested paths work too, e.g. setError('silent.email', 'Already taken') and error('silent.email').
const { submitForm, error, isFormInvalid } = useFormbit<FormData>({ initialValues, yup: schema });
const handleSubmit = () => {
submitForm(async ({ form }, setError, clearIsDirty) => {
const response = await api.createUser(form);
if (!response.ok) {
setError('silent', response.message);
return;
}
clearIsDirty();
});
};
return (
<>
{error('silent') && <div role="alert">{error('silent')}</div>}
<button disabled={isFormInvalid()} onClick={handleSubmit}>Submit</button>
</>
);A field that fails a validation becomes live-validated: from then on it is re-validated on every write, writeAll, remove and removeAll, so its error disappears as soon as the user fixes it. Check it with liveValidation(path); skip it for a single write with { noLiveValidation: true }. resetForm and initialize turn it off for every field.
Live validation is tied to the path, not to the value: if you remove a value and write it back, the path is still live-validated.
Arrays: the path includes the index, so live validation follows the index, not the item. If
friends[1].nameis live-validated and you drop the first row by writing a shorter array (e.g.write('friends', friends.filter((_, i) => i !== 0))), the invalid row moves to index 0 — which is not live-validated, so its error disappears until the nextvalidate/submitForm— whilefriends[1].namestays live-validated on an index that no longer exists (and is silently skipped).
For local development we suggest using Yalc to test your local version of formbit in your projects.
FormbitObject<
T> =object
The object returned by useFormbit() and useFormbitContext(). Holds the form
state and every method needed to read, mutate and validate the form.
T extends FormbitValues
check:
Check<Partial<T>>
Validates json against the current schema; returns the errors, or undefined if valid.
error: (
path) =>string|undefined
Returns the error message registered for path, if any.
string
string | undefined
errors:
Errors
Error messages registered since the last validation, keyed by the value's dot-path.
form: { age: 1 }
errors: { age: "Age must be greater than 18" }form:
Partial<T>
The current form values. Partial: fields may be missing until validated.
initialize:
Initialize<T>
Re-initializes the form with new initial values.
isDirty:
boolean
True once the user has interacted with the form.
isFormInvalid: () =>
boolean
True if any error is currently registered. Does not run validation.
boolean
isFormValid: () =>
boolean
True if no errors are currently registered. Does not run validation.
boolean
liveValidation: (
path) =>true|undefined
True if live-validation is active for path.
string
true | undefined
remove:
Remove<T>
Removes the value at path, sets isDirty, then validates pathsToValidate
plus every live-validated field.
removeAll:
RemoveAll<T>
Removes every given path, sets isDirty, then validates pathsToValidate
plus every live-validated field.
resetForm: () =>
void
Resets form, errors, liveValidation and isDirty back to their initial state.
void
setError:
SetError
Sets the error message at path; pass undefined to clear it.
setSchema:
SetSchema<T>
Replaces the current validation schema.
submitForm:
SubmitForm<T>
Validates the whole form and, if valid, runs the success callback to submit.
validate:
Validate<T>
Validates only path (ignores live-validated fields).
validateAll:
ValidateAll<T>
Validates only the given paths (ignores live-validated fields).
validateForm:
ValidateForm<Partial<T>>
Validates the whole form and registers any error.
write:
Write<T>
Writes value at path, sets isDirty, then validates pathsToValidate
plus every live-validated field.
writeAll:
WriteAll<T>
Writes every [path, value] pair, sets isDirty, then validates
pathsToValidate plus every live-validated field.
Errors =
object
Error messages registered since the last validation, stored as a nested object
that mirrors the shape of the form. Read a single message with error(path).
[key: string]: string | Errors | (string | Errors | undefined)[] | undefined
form: { age: 1, friends: [{ name: '' }] }
errors: { age: "Age must be greater than 18", friends: [{ name: "Name is required" }] }FormbitValues =
Record<string,unknown> &object
Base shape of every form handled by formbit: an open record of values, plus an
optional __metadata field formbit uses to carry data that must survive a
reset/initialize but must NOT be submitted.
The generic T you pass to useFormbit<T>() must extend this type.
optional__metadata?:Record<string,unknown>
FormState<
T> =object
The whole internal state of the form (everything except the validation schema).
T extends FormbitValues
errors:
Errors
form:
T
initialValues:
T
isDirty:
boolean
liveValidation:
LiveValidation
LiveValidation =
Record<string,true>
Fields currently under live-validation (re-validated on every form change). A field is added here automatically when it fails a validation. Empty by default.
form: { age: 1 }
liveValidation: { age: true }CheckErrorCallback<
T> = (json,inner,writer,setError) =>void
Invoked by check() when the given json is invalid.
T extends FormbitValues
FormState<T>
void
CheckSuccessCallback<
T> = (json,writer,setError) =>void
Invoked by check() when the given json is valid.
T extends FormbitValues
FormState<T>
void
ErrorCallback<
T> = (writer,setError) =>void
Invoked by validation methods when validation fails.
T extends FormbitValues
FormState<T>
void
SubmitSuccessCallback<
T> = (writer,setError,clearIsDirty) =>void
Invoked by submitForm() once the whole form is valid — the place to send data
to the backend. __metadata is stripped from writer.form before this runs.
T extends FormbitValues
FormState<Omit<T, "__metadata">>
() => void
void
SuccessCallback<
T> = (writer,setError) =>void
Invoked by validation methods when the form (or the validated paths) are valid.
T extends FormbitValues
FormState<T>
void
Check<
T> = (json,options?) =>ValidationError[] |undefined
See FormbitObject.check.
T extends FormbitValues
ValidationError[] | undefined
Initialize<
T> = (values) =>void
T extends FormbitValues
Partial<T>
void
Remove<
T> = (path,options?) =>void
See FormbitObject.remove.
T extends FormbitValues
string
void
RemoveAll<
T> = (arr,options?) =>void
T extends FormbitValues
string[]
void
SetError = (
path,value) =>void
string
string | undefined
void
SetSchema<
T> = (newSchema) =>void
T extends FormbitValues
void
SubmitForm<
T> = (successCallback,errorCallback?,options?) =>void
T extends FormbitValues
ErrorCallback<Partial<T>>
void
Validate<
T> = (path,options?) =>void
T extends FormbitValues
string
void
ValidateAll<
T> = (paths,options?) =>void
See FormbitObject.validateAll.
T extends FormbitValues
string[]
void
ValidateForm<
T> = (successCallback?,errorCallback?,options?) =>void
See FormbitObject.validateForm.
T extends FormbitValues
void
Write<
T> = (path,value,options?) =>void
See FormbitObject.write.
T extends FormbitValues
keyof T | string
unknown
void
WriteAll<
T> = (arr,options?) =>void
T extends FormbitValues
WriteAllValue<T>[]
void
CheckFnOptions<
T> =object
Options accepted by check().
T extends FormbitValues
optionalerrorCallback?:CheckErrorCallback<T>
optionaloptions?:ValidateOptions
optionalsuccessCallback?:CheckSuccessCallback<T>
ValidateFnOptions<
T> =object
Options accepted by the validate methods.
T extends FormbitValues
optionalerrorCallback?:ErrorCallback<Partial<T>>
optionaloptions?:ValidateOptions
optionalsuccessCallback?:SuccessCallback<Partial<T>>
WriteAllValue<
T> = [keyofT|string,unknown]
A single [path, value] pair accepted by writeAll.
T extends FormbitValues
WriteFnOptions<
T> =object&ValidateFnOptions<T>
Options accepted by the write/remove methods (validate options plus path control).
optionalnoLiveValidation?:boolean
optionalpathsToValidate?:string[]
T extends FormbitValues
ValidateOptions =
YupValidateOptions
Options forwarded to yup's validation methods. See https://github.com/jquense/yup.
ValidationError =
YupValidationError
The error object yup throws when a validation fails. See https://github.com/jquense/yup.
ValidationSchema<
T> =ObjectSchema<T>
A validation schema built with yup.object(). See https://github.com/jquense/yup.
T extends FormbitValues
MIT © [Radicalbit (https://github.com/radicalbit)]