JAVASCRIPT
Manage Complex Form State with useReducer
Learn to efficiently manage multi-field form states in React using the `useReducer` hook, ideal for forms with interdependent fields and complex logic.
import React, { useReducer } from 'react';
const formReducer = (state, action) => {
switch (action.type) {
case 'HANDLE_INPUT_CHANGE':
return {
...state,
[action.field]: action.value,
};
case 'RESET_FORM':
return action.initialState;
default:
return state;
}
};
function ComplexForm() {
const initialFormState = {
firstName: '',
lastName: '',
email: '',
};
const [formState, dispatch] = useReducer(formReducer, initialFormState);
const handleInputChange = (e) => {
dispatch({
type: 'HANDLE_INPUT_CHANGE',
field: e.target.name,
value: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form Submitted:', formState);
// You might want to dispatch a RESET_FORM here after submission
// dispatch({ type: 'RESET_FORM', initialState: initialFormState });
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name:</label>
<input
type='text'
name='firstName'
value={formState.firstName}
onChange={handleInputChange}
/>
</div>
<div>
<label>Last Name:</label>
<input
type='text'
name='lastName'
value={formState.lastName}
onChange={handleInputChange}
/>
</div>
<div>
<label>Email:</label>
<input
type='email'
name='email'
value={formState.email}
onChange={handleInputChange}
/>
</div>
<button type='submit'>Submit</button>
<button type='button' onClick={() => dispatch({ type: 'RESET_FORM', initialState: initialFormState })}>Reset</button>
</form>
);
}
export default ComplexForm;
How it works: The `useReducer` hook is ideal for managing complex state logic, especially when state transitions depend on the previous state or involve multiple interdependent values. This snippet demonstrates its use for a multi-field form. The `formReducer` function defines how state updates based on dispatched actions, centralizing the logic. `HANDLE_INPUT_CHANGE` updates individual fields, and `RESET_FORM` reverts the state to its initial values, providing a clean and scalable way to manage form interactions.