ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Context API for Themed Application State

JSX

Goal -- WPM

Ready
Exercise Algorithm Area
1const themes = {
2light: {
3backgroundColor: '#ffffff',
4textColor: '#000000',
5borderColor: '#cccccc'
6},
7dark: {
8backgroundColor: '#1a1a1a',
9textColor: '#ffffff',
10borderColor: '#444444'
11}
12};
13
14const ThemeContext = React.createContext({
15theme: themes.light,
16setTheme: () => {}
17});
18
19function ThemeProvider({ children }) {
20const [theme, setThemeState] = React.useState(themes.light);
21
22const setTheme = (themeName) => {
23if (themes[themeName]) {
24setThemeState(themes[themeName]);
25} else {
26console.warn(`Theme '${themeName}' not found. Using default light theme.`);
27setThemeState(themes.light);
28}
29};
30
31return (
32<ThemeContext.Provider value={{ theme, setTheme }}>
33{children}
34</ThemeContext.Provider>
35);
36}
37
38function useTheme() {
39const context = React.useContext(ThemeContext);
40if (context === undefined) {
41throw new Error('useTheme must be used within a ThemeProvider');
42}
43return context;
44}
45
46function ThemedButton() {
47const { theme, setTheme } = useTheme();
48
49const toggleTheme = () => {
50setTheme(theme === themes.light ? 'dark' : 'light');
51};
52
53return (
54<button
55style={{
56backgroundColor: theme.backgroundColor,
57color: theme.textColor,
58borderColor: theme.borderColor,
59padding: '10px 20px',
60cursor: 'pointer'
61}}
62onClick={toggleTheme}
63>
64Toggle Theme
65</button>
66);
67}
68
69function App() {
70return (
71<ThemeProvider>
72<div style={{ padding: '20px' }}>
73<h1>Themed Application</h1>
74<ThemedButton />
75<p style={{ color: useTheme().theme.textColor }}>This text will change color with the theme.</p>
76</div>
77</ThemeProvider>
78);
79}
Algorithm description viewbox

Context API for Themed Application State

Algorithm description:

This scenario demonstrates how to use React's Context API to manage global application state, specifically theming. The `ThemeProvider` component wraps the application, providing the current theme and a function to change it. The `useTheme` hook allows any descendant component to easily access and update the theme, ensuring consistent styling across the application without prop drilling.

Algorithm explanation:

The `ThemeProvider` uses `React.createContext` to create a context object. It then uses `ThemeContext.Provider` to wrap its children, passing down the current `theme` state and a `setTheme` function. The `useTheme` hook consumes this context using `React.useContext`. If `useTheme` is called outside of a `ThemeProvider`, it throws an error, ensuring correct usage. The `setTheme` function includes basic validation to prevent setting invalid themes. Time complexity for context updates is typically O(1) for providing and O(N) for re-rendering consuming components in the worst case, where N is the number of components that re-render. Space complexity is O(1) for the context itself, plus the state managed within the provider.

Pseudocode:

Define `themes` object with light and dark properties.
Create `ThemeContext` using `React.createContext`.
Define `ThemeProvider` component:
  Initialize `theme` state.
  Define `setTheme` function to update theme state with validation.
  Return `ThemeContext.Provider` with `theme` and `setTheme` in `value`.
Define `useTheme` hook:
  Get context using `React.useContext(ThemeContext)`.
  Throw error if context is undefined.
  Return context.
Implement example components (`ThemedButton`, `App`) using `useTheme`.