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.
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.
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.