Hook into complex form state using React

Aditya Loshali
5 min readAug 20, 2019

an alternative to some goodness of this.setState()

is everybody hooked yet ?

So, it’s been quite some time since react hooks were released. and from the looks of it, everybody is going gaga over them. Well, i understand. because i’m one of you too. Hooks got me hooked!

hooks allow us to create smaller, composable, reusable more manageable react components.

sometimes you may be using hooks to manage the form state. using useState or useReducer.

now let’s consider a scenario where you have to manage a complex form state with multiple form inputs and several different types of input. the form state may even have nested information for example a user’s address information which has it’s own sub-fields like address.addressLine1, address.addressLine2 etc.

maybe your also have to update form state based on the current state, like a toggle button.

now if you are using useState for each individual form field, then you get the ability to compute new state based on current.

const [modalActive, updateModal] = useState(false)
updateModal(prev => !prev)

but if you have too many individual form fields, like 100+, ( YESS!!. I was managing 100+ form fields ) then this approach isn’t friendly.

imagine !!..

const [firstName, setFirstName] = useState('')
const [middleName, setMiddleName] = useState('')
const [lastName, setLastName] = useState('')

so, our other option would be, useReducer

const initialState = {
firstName: '',
lastName: ''

function reducer(state, action) {
switch (action.type) {
case 'firstName':
return { firstName: action.payload };
case 'lastName':
return { lastName: action.payload };
throw new Error();

function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
placeholder="First Name"
onChange={(event) => {
type: 'firstName',
payload: event.target.value
value={state.firstName} />
Aditya Loshali

I’m a full stack web developer working with Javascript on React and Node.js everyday.