Controlled Form in React — Part 2

Muazzam Nashat
2 min readApr 11, 2021
Reducer flow, collected from https://react.christmas/2019/7

In part 1, we saw how we could set up a simple controlled React form. We used the ‘useState’ hook to store our form inputs. It looked like this:

But what would happen if the form grew bigger? What if there were multiple inputs? Our ‘handleChange’ function would look messy. Also, it would be hard to handle complex form logic.

form with useState hook

Here comes the ‘useReducer’ hook! This is an alternative to ‘useState’. According to the official React documentation:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one

The ‘useReducer’ hook takes a reducer function and an initial state as input. It returns the current state and a dispatch function. If you haven’t heard about reducers and dispatch as a concept, you can read this article. To understand the useReducer hook, you’ll need a clear understanding of reducers.

To set up the reducer, we will import the ‘useReducer’ hook. Then we need a reducer function and an initial state. For this tutorial, we will be creating a user form as we did last time. The initial state will be an empty user object.

initial state

The reducer function will accept the current state and an action and then return a new state. The action will be an object that has two values: type and payload. You can name them whatever you want; this is just the convention. The reducer function will change the state and return a new state based on the type and payload.

reducer function

We need to define our current state and a dispatch function. The dispatcher can fired to send an action to the reducer function that will change the state.

define state and dispatcher

Now, we can use a handler function to dispatch actions.

handler function

With every keystroke we’ll call ‘handleChange’ function, it will dispatch an action that will implicitly change the state. Our final form will look like this.

React’s useReducer hook is useful to handle complex state transition. While using reducer might not seem helpful in the above example, if the state grows bigger with complex logic, using the useReducer hook will help scale the application.

--

--

Muazzam Nashat

Full stack developer experienced in Ruby and JavaScript based programming.