react-use-form-state

Managing form state in React can be a bit unwieldy sometimes. There are plenty of great solutions already available that make managing form states a breeze. However, many of those solutions are opinionated, packed with tons of features that may end up not being used, and/or require shipping a few extra bytes.

Luckily, the recent introduction of React Hooks and the ability to write custom Hooks have enabled new possibilities when it comes to sharing state logic. Form state is no exception.

react-use-form-state is a small React Hook that attempts to simplify managing form state, using the native form input elements you are familiar with.

Getting started

To get it started, add react-use-form-state to your project:

npm install --save react-use-form-state

Note that react-use-form-state requires react@^16.8.0 as a peer dependency.

Basic usage

import { useFormState } from 'react-use-form-state'; export default function SignUpForm({ onSubmit }) {

const [formState, { text, email, password, radio }] = useFormState(); function handleSubmit(e) {

// ...

} return (

<form onSubmit={handleSubmit}>

<input {...text('name')} />

<input {...email('email')} required />

<input {...password('password')} required minLength="8" />

<input {...radio('plan', 'free')} />

<input {...radio('plan', 'premium')} />

</form>

);

}

From the example above, as the user fills in the form, the formState object will look something like this:

{

values: {

name: 'Mary Poppins',

email: 'mary@example.com',

password: '1234',

plan: 'free',

},

touched: {

name: true,

email: true,

password: true,

plan: true,

},

validity: {

name: true,

email: true,

password: false,

plan: true,

},

errors: {

password: 'Please lengthen this text to 8 characters or more',

},

clear: Function,

clearField: Function,

reset: Function,

resetField: Function,

setField: Function,

}

Initial state

useFormState takes an initial state object with keys matching the names of the inputs.

export default function RentCarForm() {

const [formState, { checkbox, radio, select }] = useFormState({

trip: 'roundtrip',

type: ['sedan', 'suv', 'van'],

});

return (

<form>

<select {...select('trip')}>

<option value="roundtrip">Same Drop-off</option>

<option value="oneway">Different Drop-off</option>

</select>

<input {...checkbox('type', 'sedan')} />

<input {...checkbox('type', 'suv')} />

<input {...checkbox('type', 'van')} />

<button>Submit</button>

</form>

);

}

Check out the API documentation section for an in-depth dive.