Blog>
Snippets

Form Input Handling with useReducer

Manage the state of multiple form inputs with useReducer by handling changes in a scalable way, suitable for complex forms.
import React, { useReducer } from 'react';

// Define the types of actions to handle
const INPUT_CHANGE = 'INPUT_CHANGE';

// Define the form's initial state
const initialFormState = {
    username: '',
    email: '',
    password: ''
};

// Define the reducer function to handle actions
function formReducer(state, action) {
    switch (action.type) {
        case INPUT_CHANGE:
            const { name, value } = action.payload;
            return {
                ...state,
                [name]: value
            };
        default:
            return state;
    }
}

const MyForm = () => {
    const [formState, dispatch] = useReducer(formReducer, initialFormState);

    // Handle input change events
    const handleInputChange = (event) => {
        const { name, value } = event.target;
        dispatch({
            type: INPUT_CHANGE,
            payload: { name, value }
        });
    };

    return (
        <form>
            <input
                name='username'
                value={formState.username}
                onChange={handleInputChange} />
            <input
                name='email'
                value={formState.email}
                onChange={handleInputChange} />
            <input
                name='password'
                value={formState.password}
                onChange={handleInputChange} />
        </form>
    );
};

export default MyForm;
This code snippet defines a React component with a form using the useReducer hook to handle states for multiple inputs. The `formReducer` function updates the state based on the dispatched action, which contains the input's name and value. The `MyForm` component includes an event handler `handleInputChange` that dispatches the corresponding `INPUT_CHANGE` action when the input field changes. Each input field is controlled with its state from the reducer.