Skip to content

Instantly share code, notes, and snippets.

@17twenty
Created June 26, 2025 22:11
Show Gist options
  • Save 17twenty/018daf5e77f12ab70625de79eb4d750d to your computer and use it in GitHub Desktop.
Save 17twenty/018daf5e77f12ab70625de79eb4d750d to your computer and use it in GitHub Desktop.
Example of using React with useReducer
import { useReducer } from 'react';
const initialFormState: FormState = {
name: '',
email: '',
isSubmitting: false,
isSubmitted: false,
submitError: null,
};
function ProfileForm() {
const [state, dispatch] = useReducer(formReducer, initialFormState);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
dispatch({
type: 'UPDATE_FIELD',
field: e.target.name as keyof UserProfile,
value: e.target.value,
});
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
dispatch({ type: 'SUBMIT_START' });
try {
// Simulate API call
await new Promise((res) => setTimeout(res, 1000));
dispatch({ type: 'SUBMIT_SUCCESS' });
} catch (error) {
dispatch({ type: 'SUBMIT_ERROR', error: 'Submission failed' });
}
};
return (
<form onSubmit={handleSubmit}>
<input
name="name"
value={state.name}
onChange={handleChange}
disabled={state.isSubmitting}
/>
<input
name="email"
value={state.email}
onChange={handleChange}
disabled={state.isSubmitting}
/>
<button type="submit" disabled={state.isSubmitting}>
{state.isSubmitting ? 'Submitting...' : 'Submit'}
</button>
{state.submitError && <p style={{ color: 'red' }}>{state.submitError}</p>}
{state.isSubmitted && <p style={{ color: 'green' }}>Profile updated!</p>}
</form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment