Toggle with Context + Reducer
Difficulty: Core
Problem Statementβ
Manage toggleable shared state (language/theme) with reducer + Context.
Live Demoβ
Try the running app below β this is the target behavior for the challenge.
Toggle with Context + Reducer β Live Demo
Current language: javascript
What Interviewers Expectβ
- Reducer remains pure.
- Context hides implementation details from consumers.
- Predictable action flow.
Step-by-Step Implementationβ
Step 1 β Reducerβ
Switch language between two known values.
const toggleReducer = (state) => ({ language: state.language === 'javascript' ? 'java' : 'javascript' });
Step 2 β Provider + consumerβ
Wrap subtree and consume { language, toggle }.
<ToggleCtx.Provider value={{ language: state.language, toggle: () => dispatch({}) }}>
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, useReducer} from 'react';
const ToggleCtx = createContext(null);
const toggleReducer = (state) => ({
language: state.language === 'javascript' ? 'java' : 'javascript',
});
function ToggleConsumer() {
const {language, toggle} = useContext(ToggleCtx);
return (
<div>
<p>
Current language: <strong>{language}</strong>
</p>
<button type="button" onClick={toggle}>
Toggle
</button>
</div>
);
}
export default function App() {
const [state, dispatch] = useReducer(toggleReducer, {language: 'javascript'});
return (
<ToggleCtx.Provider value={{language: state.language, toggle: () => dispatch({})}}>
<ToggleConsumer />
</ToggleCtx.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.