Performance: Handling input fields
This affects interaction responsiveness and rendering speed when users type or change input values.
function Input() { const [value, setValue] = React.useState(''); const handleChange = React.useCallback(e => setValue(e.target.value), [setValue]); return <input value={value} onChange={handleChange} />; }
function Input() { const [value, setValue] = React.useState(''); return <input value={value} onChange={e => setValue(e.target.value)} />; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Controlled input with state update on every keystroke | Many updates | 1 per keystroke | High due to frequent layout | [X] Bad |
| Controlled input with memoized handlers and calculations | Many updates | 1 per keystroke | Medium due to optimized JS | [!] OK |
| Uncontrolled input with ref and no state updates | Minimal updates | 0 during typing | Low paint cost | [OK] Good |
useState when handling input fields in React?e contains the input element in e.target, and its value is in e.target.value.e.target.value inside the arrow function.import React, { useState } from 'react';
function InputExample() {
const [text, setText] = useState('');
return (
<div>
<input value={text} onChange={e => setText(e.target.value)} />
<p>You typed: {text}</p>
</div>
);
}text. Typing updates text via setText.text value, so typing 'hello' shows 'You typed: hello'.function MyInput() {
const [value, setValue] = useState('');
function handleChange() {
setValue(e.target.value);
}
return <input value={value} onChange={handleChange} />;
}e.target.value but does not receive e as a parameter, causing a ReferenceError.e as a parameter fixes the error: function handleChange(e) { setValue(e.target.value); }.firstName and lastName, and update their values independently using a single useState object. Which code snippet correctly updates the state when either input changes?const [form, setForm] = useState({ firstName: '', lastName: '' });
// Which onChange handler is correct?
A) onChange={e => setForm({ [e.target.name]: e.target.value })}
B) onChange={e => setForm(prev => ({ ...prev, [e.target.name]: e.target.value }))}
C) onChange={e => setForm({ form, [e.target.name]: e.target.value })}
D) onChange={e => setForm({ form: { [e.target.name]: e.target.value } })}Pass the test and this pattern moves unknown