Course contentsShow
← React
Lesson 340 of 2,39610. useState BasicsFree lesson

String State for Text Input

Managing text input values with useState for controlled components.

String State for Text Input

You'll learn: How to use useState with string values to control text input fields in React.

The Core Idea

When you want to capture what a user types into an input box, you store that text in state as a string. You connect the input's value to your state variable, and update state with every keystroke using an onChange handler. This makes React the "single source of truth" for what's displayed — we call this a controlled component.

How It Works

You initialize state with an empty string (or a default value). The input displays whatever is in state, and when the user types, you call the setter function to update that state with the new text. React re-renders, showing the updated value.

Basic Pattern

function NameForm() {
  const [name, setName] = useState('');

  return (
    <div>
      <input 
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <p>You typed: {name}</p>
    </div>
  );
}

Here, name holds the current text. The value={name} makes the input display it. The onChange handler fires on every keystroke, passing an event object (e). We read e.target.value (the new input content) and pass it to setName.

Why This Matters

This pattern gives you complete control. You can read the current value anytime, validate it before setting, transform it (like forcing uppercase), or clear it with a button click. The input reflects state, and state reflects the input — they're synchronized.

Key Takeaway: Use string state with value and onChange to control text inputs, keeping React in sync with what the user types.