All quizzesEasy
Local State & Lifting
Preview — 3 of 10 questions
Where should state live?
javascript
// Option A — local state in the component that needs it:
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
// Option B — global state in app-level store:
// store.count used by a single Counter componentAAll state should be global — easier to access everywhere
BAll state should be local — global state is always a bad pattern
CState should live as close as possible to where it's used — local state for component-specific data; only lift or globalize when multiple components need the same data
DState should always be in the root App component
How does the Context API work?
javascript
const UserContext = createContext(null);
function App() {
const [user, setUser] = useState({ name: "Alice" });
return (
<UserContext.Provider value={{ user, setUser }}>
<Layout />
</UserContext.Provider>
);
}
function Avatar() {
const { user } = useContext(UserContext); // no prop drilling!
return <img alt={user.name} src={user.avatar} />;
}AContext provides a way to share state across components without prop drilling — Provider wraps the tree; any descendant can read the value via useContext
BContext replaces useState — you don't need both
CContext only works one level deep
DEvery component in <Layout /> automatically re-renders when context changes
Which scenario is best for Context?
javascript
// Scenario A:
<ParentComponent>
<ChildComponent color="blue" /> {/* only child uses color */}
</ParentComponent>
// Scenario B:
<App>
<Header /> {/* shows current user name */}
<Sidebar /> {/* shows user avatar */}
<MainContent /> {/* shows user-specific content */}
<Footer /> {/* shows user email */}
</App>AScenario A suits props (direct parent-child); Scenario B suits Context — the same user data is needed in many unrelated components at different depths
BAlways use Context — props are verbose
CScenario A suits Context; Scenario B suits props
DContext and props are interchangeable with no performance difference
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.