Skip to content

Controlled and Uncontrolled Props

The Course
•
20 min study

An <input> can be used two ways. With value and onChange, the parent owns the text: it's controlled. With defaultValue, the input keeps its own text, and the parent only sets where it starts: it's uncontrolled. Good reusable components offer the same choice.

One Rating, two ways React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Rating from "./Rating.jsx"; export default function App() { const [difficulty, setDifficulty] = useState(3); return ( <main> <h1>Rate today's topics</h1> <section className="panel"> <h2>Reducers (uncontrolled)</h2> <Rating label="Reducers" defaultValue={2} /> </section> <section className="panel"> <h2>Context (controlled)</h2> <Rating label="Context" value={difficulty} onChange={setDifficulty} /> <p className="muted">The parent knows: {difficulty} stars.</p> <button onClick={() => setDifficulty(0)}>Clear from the parent</button> </section> </main> ); } import { useControllableState } from "./useControllableState.js"; const STARS = [1, 2, 3, 4, 5]; // Controlled with value + onChange, or uncontrolled with defaultValue. export default function Rating({ label, value, defaultValue = 0, onChange }) { const [rating, setRating] = useControllableState({ value, defaultValue, onChange }); return ( <div className="stars" role="radiogroup" aria-label={label}> {STARS.map((star) => ( <button key={star} role="radio" aria-checked={star === rating} className={star <= rating ? "on" : undefined} aria-label={`${star} star${star > 1 ? "s" : ""}`} onClick={() => setRating(star)} > ★ </button> ))} <span className="muted"> {rating} of 5</span> </div> ); } import { useState } from "react"; // State that a parent can control (value + onChange) or leave to the // component (defaultValue), like <input value> versus <input defaultValue>. export function useControllableState({ value, defaultValue, onChange }) { const [inner, setInner] = useState(defaultValue); const isControlled = value !== undefined; const current = isControlled ? value : inner; function setValue(next) { if (!isControlled) setInner(next); onChange?.(next); } return [current, setValue]; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Click stars in both ratings, then press Clear from the parent.

  • Reducers is uncontrolled: defaultValue={2}. The rating keeps its own state, and the parent never needs to know.
  • Context is controlled: value={difficulty} and onChange={setDifficulty}. The parent always knows the rating, and can change it, as the button does.

One hook for both

useControllableState decides which mode it's in by whether value was passed:

JavaScript
const isControlled = value !== undefined;
const current = isControlled ? value : inner;

When the rating changes, it updates its own state only when uncontrolled, and always tells the caller through onChange. Every component in a kit can share this hook, so they all behave the same way:

JavaScript
function setValue(next) {
  if (!isControlled) setInner(next);
  onChange?.(next);
}

Predict

Change the Context rating to value={difficulty} with no onChange. Click a star. What happens?

Check your prediction

Nothing: the rating stays on 3. It's controlled, so it shows whatever the parent says, and the parent never hears about the click. It's the same as an <input value> without onChange. React warns about that for inputs; your own components can do the same.

Don't switch modes

A component shouldn't change from uncontrolled to controlled while it's on the screen: if value goes from undefined to a number, the state it kept so far is ignored. React warns about this for inputs too. Callers should pick one mode and keep it, which usually means initialising state with a value, not undefined.

Your turn

Exercise

Warn like React does

In useControllableState, log a warning when a component is controlled but has no onChange: This component is controlled (it has a value) but has no onChange, so it can't change. Log when that condition first becomes true, not on every render. If the caller fixes the prop and later removes it again, a new warning is useful. StrictMode may repeat the initial effect in development.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import Rating from "./Rating.jsx"; export default function App() { const [difficulty, setDifficulty] = useState(3); return ( <main> <h1>Rate today's topics</h1> <section className="panel"> <h2>Reducers (uncontrolled)</h2> <Rating label="Reducers" defaultValue={2} /> </section> <section className="panel"> <h2>Context (controlled)</h2> <Rating label="Context" value={difficulty} onChange={setDifficulty} /> <p className="muted">The parent knows: {difficulty} stars.</p> <button onClick={() => setDifficulty(0)}>Clear from the parent</button> </section> </main> ); } import { useControllableState } from "./useControllableState.js"; const STARS = [1, 2, 3, 4, 5]; // Controlled with value + onChange, or uncontrolled with defaultValue. export default function Rating({ label, value, defaultValue = 0, onChange }) { const [rating, setRating] = useControllableState({ value, defaultValue, onChange }); return ( <div className="stars" role="radiogroup" aria-label={label}> {STARS.map((star) => ( <button key={star} role="radio" aria-checked={star === rating} className={star <= rating ? "on" : undefined} aria-label={`${star} star${star > 1 ? "s" : ""}`} onClick={() => setRating(star)} > ★ </button> ))} <span className="muted"> {rating} of 5</span> </div> ); } import { useState } from "react"; // State that a parent can control (value + onChange) or leave to the // component (defaultValue), like <input value> versus <input defaultValue>. export function useControllableState({ value, defaultValue, onChange }) { const [inner, setInner] = useState(defaultValue); const isControlled = value !== undefined; const current = isControlled ? value : inner; function setValue(next) { if (!isControlled) setInner(next); onChange?.(next); } return [current, setValue]; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Two separate questions: when is the component in the broken state, and when should the warning be logged? The first is a true/false fact you can work out from the props on any render. The second is "when that fact becomes true", which is about a change between renders, not about one render.

Hint 2: a first step

Work out the true/false fact first and log it during render, to check it: pass value={3} with no onChange and click the stars a few times. The warning repeats on every render, which is what React avoids. Which tool runs code after a render only when a value it depends on has changed?

Show one solution
JavaScript
import { useEffect, useState } from "react";

export function useControllableState({ value, defaultValue, onChange }) {
  const [inner, setInner] = useState(defaultValue);
  const isControlled = value !== undefined;
  const missingOnChange = isControlled && !onChange;

  useEffect(() => {
    if (missingOnChange) {
      console.warn("This component is controlled (it has a value) but has no onChange, so it can't change.");
    }
  }, [missingOnChange]);

  // ...rest unchanged
}

Was this article helpful?

Your response is saved on this device.