Repo of the Day
zanlib0/fractal-form
Published: Mar 27, 2023
Open repository ↗An experimental React form library using lenses.
Summary
fractal-form is an experimental React form library that uses lenses from functional programming to read and update form data. Lenses are modular data accessors for immutable state, and this library's lenses are self-similar, so the same patterns work at any level of nesting. The project is inspired by André Staltz's use-profunctor-state.
What it is useful for
This library is useful when you are building forms in React and want a structured way to manage values, errors, and touched state without manually threading props. Because lenses are self-similar, a form component written for a top-level field can be reused inside a nested form by passing the appropriate inner lens down. That makes it suited to forms that are deeply nested or built from many small components over time.
How engineers can use it
The README documents one install command: npm install fractal-form. From the README's basic example, you call useFractalForm({ name: '' }) in a component, which returns useFormLens along with value, error, touched, and set* / use*Lens hooks. You then call useLensField(useFormLens, 'name') to get a field object whose spread props (value, onChange, error, touched, onBlur) go straight onto an input. The third argument to useLensField is an optional validator that takes the parent value and the new field value and returns an error string or null, as shown in the validateName snippet in the API Reference.
If you only need state with a lens rather than a full form, useLensState works like React's useState but returns an extra useLens hook whose view and update functions stay in sync with the source state, so setName('Alice') updates both the focused value and the parent object. lensForProp('name') is a helper that returns the [view, update] pair for a given key, replacing the inline functions in the useLensState example. The README notes that lenses are memoized, so wrapping consumers in React.memo should be enough to avoid unnecessary rerenders.
Caveats worth flagging: the README explicitly labels this library "experimental," warns that the bare set* functions from useFractalForm are best avoided, and points to only one example file (src/Example.js), so anything beyond the documented APIs should be confirmed there.