Who's the Boss in the Text Field?
In a regular HTML file, a text field (<input />) knows itself what's written in it. It stores this data inside itself.
But in React there's a rule: " All state must be under my control " . This creates a conflict.
1. Controlled Components: React Dictatorship
This is the most popular path. We tell the input: " Your value is what lies in my useState. Not a step to the left! " .
- How it works: When user presses a key,
onChangetriggers. We updatestate. React redraws the component and draws the new value in the input. - Analogy: You're driving a car where the steering wheel is rigidly connected to the wheels. Where you turn in code — the interface goes.
- Plus: You can instantly change input (e.g., forbid entering digits or automatically capitalize the first letter).
- Minus: Every character causes a redraw of the entire component. If the form is huge — this can " fry " .
2. Uncontrolled Components: Trusting the Browser
Here we say: " Okay, input, live your life. I won't watch your every breath " .
- How it works: We use
useRef. The input stores text itself, and we go to it for data only when the user presses the " Send " button. - Analogy: You're riding in a taxi. You don't know how the driver turns the steering wheel, you just ask at the end: " Well, did we arrive? " .
- Plus: This works maximally fast because there are no extra redraws.
- Minus: Harder to do " live " validation (e.g., paint the field red immediately when an error is made).
3. What to Choose?
- Choose Controlled (state) if: You need instant reaction (list filtering on input, validation on the fly, complex phone masks).
- Choose Uncontrolled (ref) if: You have a huge form (e.g., a questionnaire with 100 fields) and you're fighting for every frame of performance.
Remember: In 90% of cases, React uses controlled components. This makes code predictable and easy to debug.