Context API β Language Toggle
Difficulty: Core
Problem Statementβ
Share selected language across components using Context. Show current language and toggle between options.
Live Demoβ
Try the running app below β this is the target behavior for the challenge.
Context API β Language Toggle β Live Demo
Favorite programming language: JavaScript
What Interviewers Expectβ
- Create context + provider at app/subtree root.
- Consume with
useContextin child components. - Avoid prop drilling.
Step-by-Step Implementationβ
Step 1 β Create contextβ
Define context with default shape.
const LangCtx = createContext(null);
Step 2 β Provider stateβ
Hold language in parent and pass value + toggle function.
<LangCtx.Provider value={{ language, toggleLanguage }}>
Step 3 β Consumer UIβ
Read context in child and render current language.
const { language, toggleLanguage } = useContext(LangCtx);
Complete Implementationβ
Copy-paste ready single-file solution. Use this as your reference after attempting the challenge yourself, or paste it into CodeSandbox / StackBlitz to run locally.
App.jsx
import React, {createContext, useContext, useMemo, useState} from 'react';
const LangCtx = createContext(null);
function LangPanel() {
const {language, toggleLanguage} = useContext(LangCtx);
return (
<div>
<p id="favoriteLanguage">
Favorite programming language: <strong>{language}</strong>
</p>
<button id="changeFavorite" type="button" onClick={toggleLanguage}>
Toggle language
</button>
</div>
);
}
export default function App() {
const languages = useMemo(() => ['JavaScript', 'Python'], []);
const [language, setLanguage] = useState(languages[0]);
const toggleLanguage = () => {
setLanguage((curr) => (curr === languages[0] ? languages[1] : languages[0]));
};
return (
<LangCtx.Provider value={{language, toggleLanguage}}>
<LangPanel />
</LangCtx.Provider>
);
}
Final Checklistβ
- UI works for primary flow
- Edge cases handled (empty/disabled/loading where relevant)
- State updates are immutable
- Components are readable and reasonably split
- You can explain trade-offs out loud in an interview
Next Challengeβ
Continue to the next item in the sidebar when you're comfortable implementing this from scratch in 30β45 minutes.