ReactMedium
Controlled Pattern?
The controlled pattern means a component's important state is owned by its parent: the parent passes the current value (value, open, selected) and a change handler (onChange, onOpenChange), and the component only renders and requests changes. Good reusable components support both controlled and uncontrolled use (value versus defaultValue).
Controlled vs uncontrolled components
- Controlled:
<Dialog open={isOpen} onOpenChange={setIsOpen} />. The parent can open it from anywhere, sync it with the URL, or block closing. - Uncontrolled:
<Dialog defaultOpen={false} />. The component manages its own state; simpler for basic use.
Supporting both
- Accept
value,defaultValueandonChange. - If
value !== undefined, use it (controlled); otherwise use internal state initialized fromdefaultValue. - Always call
onChangewhen the user requests a change. - Do not switch between modes during the component's lifetime; warn in development if it happens.
This is how native inputs, Radix UI and React Aria components work. A reusable useControllableState hook makes it easy.
Benefits of control
- Single source of truth in the parent.
- Validation or transformation before accepting a change.
- Coordination between components (one accordion open at a time).
- Persistence in the URL or a store.
Related: state reducer pattern
Some libraries let callers pass a reducer to intercept internal state changes, offering control without managing all state.
Code example
tsx
1import { useState } from "react";23function useControllableState<T>({ value, defaultValue, onChange }: { value?: T; defaultValue: T; onChange?: (v: T) => void }) {4 const [internal, setInternal] = useState(defaultValue);5 const isControlled = value !== undefined;6 const current = isControlled ? value : internal;7 const setValue = (next: T) => {8 if (!isControlled) setInternal(next);9 onChange?.(next);10 };11 return [current, setValue] as const;12}1314type ToggleProps = { checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (v: boolean) => void; label: string };1516export function Switch({ checked, defaultChecked = false, onCheckedChange, label }: ToggleProps) {17 const [on, setOn] = useControllableState({ value: checked, defaultValue: defaultChecked, onChange: onCheckedChange });18 return (19 <button role="switch" aria-checked={on} onClick={() => setOn(!on)}>20 {label}: {on ? "On" : "Off"}21 </button>22 );23}2425export function Settings() {26 const [notifications, setNotifications] = useState(true);27 return (28 <>29 <Switch label="Dark mode" defaultChecked /> {/* uncontrolled */}30 <Switch label="Notifications" checked={notifications} onCheckedChange={(v) => confirm("Change?") && setNotifications(v)} /> {/* controlled */}31 </>32 );33}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.