Theme Toggle With Context
ReactJS
Hard
6 views
Problem Description
Create a light/dark theme toggle using React context.
Output Format
Render a React component.
Constraints
Provide theme + toggle from context and consume it.
Official Solution
import React, { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext(null);
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({ theme, toggle: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')) }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('ThemeProvider missing');
return ctx;
}
function Panel() {
const { theme, toggle } = useTheme();
const styles = theme === 'dark'
? { background: '#111', color: '#fff', border: '1px solid #333' }
: { background: '#fff', color: '#124', border: '1px solid #eee' };
return (
<div style={{ borderRadius: 16, padding: 16, width: 420, ...styles }}>
<strong>meetcode theme</strong>
<p style={{ margin: '10px 0', color: theme === 'dark' ? '#ddd' : '#555' }}>Current: {theme}</p>
<button type='button' onClick={toggle} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Toggle</button>
</div>
);
}
export default function App() {
return (
<div style={{ padding: 16 }}>
<ThemeProvider>
<Panel />
</ThemeProvider>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!