React Context API — React Technical Interview Questions & Answers
React Context API
React Context API
- The ‘new’ Context API (16.3+) is createContext + Provider + Consumer/useContext. It replaced the barely-used legacy contextTypes API. Today you almost always useContext, not <Theme.Consumer>.
- value should be stable when possible — a new {{}} object every render makes all consumers update. Memoize the value or split contexts (theme vs user).
- React Context API — on screen: Asha. Deep child reads user without five prop layers.
Provider value
│
▼
deep child
useContextTechnical Interview Tip: New vs legacy + stable Provider value.
Code Examples for React Context API
Example
// Context API
import { createContext, useContext, useState } from "react";
const Auth = createContext(null);
export default function App() {
const [user, setUser] = useState({ name: "Asha" });
return (
<Auth.Provider value={{ user, setUser }}>
<Who />
</Auth.Provider>
);
}
function Who() {
const { user } = useContext(Auth);
return <p>{user.name}</p>;
}
React Context API — on screen: Asha. Deep child reads user without five prop layers.
How to Explain React Context API to an Interviewer
Explain React Context API as if you are teaching a junior — definition, then one tiny UI.
API : createContext + Provider + useContext. Old : contextTypes.
What does the example show on screen (or print), and what does that prove?
React Context API — on screen: Asha
What mistake do freshers make with React Context API?
Perf : stable value object.