tezvyn:

Single useState object for multi-input forms

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

scalable form state and immutable updates.

OUTLINE

hold all fields in one state object, use a generic handler keyed by field name, and update immutably by spreading previous state.

WHAT THIS TESTS This checks that you can scale form state without a hook per field and that you understand React's immutable update requirement for objects in state.

A GOOD ANSWER COVERS Instead of a separate useState per input, you keep the entire form in a single object, for example useState with an initial object like name empty, email empty, password empty. You write one generic change handler that accepts a field key and the new value and updates state immutably. The key detail is immutability: you must not mutate the existing object; you create a new object by spreading the previous state and overriding the single changed field, and you should use the functional updater form so concurrent updates use the latest state. A typical handler is setForm(prev spread, then field colon value). Each TextInput then binds value to form for its field and calls onChangeText with a closure that supplies that field name. This scales to many fields, keeps related data together, and makes validation and submission straightforward because the whole payload is one object.

COMMON WRONG ANSWERS Mutating form directly then calling the setter, which can skip re-renders and cause stale UI. Calling the setter with an object containing only the changed field, which discards the other fields. Forgetting the functional updater, risking lost updates when several fields change quickly.

LIKELY FOLLOW-UPS Why must updates be immutable? When would useReducer be cleaner? How do you handle nested form objects?

ONE CONCRETE EXAMPLE State form holds name, email, password. A handler handleChange(field, value) calls setForm(prev returning a spread of prev with field set to value). The email TextInput uses value form.email and onChangeText text calling handleChange('email', text). Typing in one field updates only email while name and password are preserved through the spread.

Read the original → react.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.