Skip to main content

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.

🌟 Join the JavaScript360 community

Connect with fellow JS developers, and get free interview prep, React challenges, and DSA guides.

Join on WhatsApp →