Course contentsShow
← React
Lesson 505 of 2,39614. Uncontrolled ComponentsFree lesson

Mixing defaultValue with Refs

Combine defaultValue for initial state with useRef to read or programmatically update the input when needed.

Mixing defaultValue with Refs

What you'll learn: How to combine defaultValue for initial state with useRef to read or programmatically manipulate uncontrolled inputs when needed.

The Best of Both Worlds

You've learned to use defaultValue to set an input's starting value, and you've learned to use refs to read values without re-renders. These two features work perfectly together, giving you an uncontrolled component that starts with a reasonable initial state and can be accessed or manipulated when you need it.

How It Works

Set defaultValue to provide the initial content, and attach a ref to read or programmatically change the input later:

function LoginForm() {
  const emailRef = useRef(null);

  function handleSubmit(e) {
    e.preventDefault();
    const email = emailRef.current.value;
    console.log('Submitted:', email);
  }

  function clearEmail() {
    // Programmatically clear the input
    emailRef.current.value = '';
    emailRef.current.focus();
  }

  return (
    <form onSubmit={handleSubmit}>
      <input 
        ref={emailRef}
        type="email"
        defaultValue="user@example.com"
      />
      <button type="submit">Submit</button>
      <button type="button" onClick={clearEmail}>Clear</button>
    </form>
  );
}

Why This Pattern Works

The input starts with "user@example.com" displayed, but React doesn't control it afterward. You can read the current value anytime via emailRef.current.value without causing re-renders. You can also set .value to programmatically update the input—something you can't do with controlled components without triggering renders.

Think of it like setting the thermostat's default temperature at installation, but being able to manually adjust it whenever needed without the system logging every single change.

Key Takeaway: Combining defaultValue with useRef gives you an uncontrolled input that starts with meaningful initial content and can be read or updated programmatically without triggering re-renders—ideal for forms where live validation isn't needed.