Skip to content

feat: add useFormsy hook as alternative to withFormsy HOC#762

Open
ThibautMarechal wants to merge 1 commit into
formsy:masterfrom
ThibautMarechal:feat/use-formsy-hook
Open

feat: add useFormsy hook as alternative to withFormsy HOC#762
ThibautMarechal wants to merge 1 commit into
formsy:masterfrom
ThibautMarechal:feat/use-formsy-hook

Conversation

@ThibautMarechal

@ThibautMarechal ThibautMarechal commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Closes #761

What

Adds a useFormsy<V>(options) hook that provides the same field integration as withFormsy without the HOC wrapper.

export function useFormsy<V>(options: UseFormsyOptions<V>): UseFormsyResult<V>

New exports:

  • useFormsy — the hook
  • UseFormsyOptions<V> — same shape as WrapperProps<V> (name, value, validations, …)
  • UseFormsyResult<V> — same shape as InjectedProps<V> + value: V

Usage

import { useFormsy } from 'formsy-react';

function MyInput({ name, label }: { name: string; label: string }) {
  const { value, setValue, showError, errorMessage } = useFormsy<string>({ name });

  return (
    <div>
      <label>{label}</label>
      <input value={value ?? ''} onChange={(e) => setValue(e.target.value)} />
      {showError && <span>{String(errorMessage)}</span>}
    </div>
  );
}

With validations:

const { value, setValue, showError, errorMessage } = useFormsy<string>({
  name: 'email',
  validations: { isEmail: true },
  validationErrors: { isEmail: 'Please enter a valid email' },
  required: true,
});

How it works

useFormsy mirrors the lifecycle of the WithFormsyWrapper class component:

Class component Hook equivalent
Constructor — seed state, setValidations useState initial value + useEffect([], [])
componentDidMountattachToForm useEffect (mount)
componentWillUnmountdetachFromForm useEffect cleanup
componentDidUpdate — sync value useEffect([valueProp])
componentDidUpdate — sync validations useEffect([validationsProp, requiredProp])
setState called by form context Mutable ref + useState setter

The form context (attachToForm, validate, …) operates on a component-like ref object that forwards state reads/writes to the React state, keeping both in sync.

Backward compatibility

  • withFormsy is unchanged
  • useFormsy is a purely additive export
  • No breaking changes

@ThibautMarechal

Copy link
Copy Markdown
Contributor Author

This is more a proposal. If you agree that it's a good idea, I'll be happy to work on it in order to add tests and share more common code between the hoc & hook :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add useFormsy hook as alternative to withFormsy HOC

1 participant