Theme Context Toggle
ReactJS
Hard
5 views
Problem Description
Create a ThemeProvider that toggles light/dark and updates styles.
Output Format
Render a React component.
Constraints
Use Context + state in provider and a hook to consume it.
Official Solution
import React, { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext(null);
function ThemeProvider({ children }) {
const [mode, setMode] = useState('light');
const value = useMemo(() => ({ mode, toggle: () => setMode((m) => m === 'light' ? 'dark' : 'light') }), [mode]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
function useTheme() {
const v = useContext(ThemeContext);
if (!v) throw new Error('ThemeProvider missing');
return v;
}
function Page() {
const { mode, toggle } = useTheme();
const isDark = mode === 'dark';
return (
<div style={{ padding: 16, minHeight: 200, background: isDark ? '#0b1220' : '#f8fafc', color: isDark ? '#f8fafc' : '#111827', borderRadius: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<strong>meetcode</strong>
<button type='button' onClick={toggle} style={{ padding: '8px 12px', borderRadius: 12, border: 0, background: isDark ? '#0b5' : '#111827', color: '#fff' }}>
Toggle {isDark ? 'Light' : 'Dark'}
</button>
</div>
<p style={{ marginTop: 12, color: isDark ? '#d1d5db' : '#374151' }}>Theme is stored in provider state.</p>
</div>
);
}
export default function App() {
return (
<ThemeProvider>
<Page />
</ThemeProvider>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!