All quizzesMedium
Component Patterns
Preview — 3 of 10 questions
Two sibling components need to share state. What is the correct pattern?
javascript
// Scenario: Slider and Display need to share `value`
function Slider({ value, onChange }) {
return <input type="range" value={value} onChange={(e) => onChange(+e.target.value)} />;
}
function Display({ value }) {
return <p>Value: {value}</p>;
}
function App() {
const [value, setValue] = useState(50);
return (
<>
<Slider value={value} onChange={setValue} />
<Display value={value} />
</>
);
}AError — only one component can receive the state at a time
BBoth components should have their own internal state and sync with useEffect
CThe state is "lifted" to the nearest common ancestor (App) and passed down as props — this is the standard React pattern
DThis creates infinite re-renders because setValue is recreated each render
What is a controlled input?
javascript
// Uncontrolled:
function Uncontrolled() {
return <input type="text" />;
}
// Controlled:
function Controlled() {
const [value, setValue] = useState("");
return (
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}AA controlled input's value is driven by React state — React is the "single source of truth"; every keystroke updates state which re-renders the input
BA controlled input validates user input automatically
CA controlled input prevents the user from typing certain characters
DControlled inputs are slower than uncontrolled because of re-renders
What is the difference between these two setCount calls?
javascript
function Counter() {
const [count, setCount] = useState(0);
const handleTripleIncrement = () => {
// Version A:
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
// Version B:
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
};
}ABoth increment count by 3
BBoth increment by 1 — React batches all setCount calls into one
CVersion A increments by 3; Version B increments by 1
DVersion A increments by 1 (stale closure); Version B increments by 3 (functional update)
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.