CodeBlanks Logo Icon CodeBlanks

Challenge: Theme provider

Write a dark/light theme provider with context + useReducer.

Challenge: Theme provider

In this challenge you write a theme context and a ThemeProvider component. The theme state holds "light" or "dark"; toggleTheme switches them.

The context value provides { theme, toggleTheme }. Consuming components read it with useContext.

This is the standard pattern for dark/light theme switching.

Practice Write ThemeProvider

Create ThemeContext with createContext. Write a ThemeProvider component: keep theme in useState("light"), define a toggleTheme function (light becomes dark, dark becomes light). Provide value={{ theme, toggleTheme }} via ThemeContext.Provider and render children. Export both ThemeProvider and ThemeContext.

Starter code

App.jsx
import { createContext, useState } from "react";

// ThemeContext ve ThemeProvider'ı buraya yaz

Sample solution

App.jsx
import { createContext, useState } from "react";

export const ThemeContext = createContext();

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  const toggleTheme = () => setTheme(theme === "light" ? "dark" : "light");
  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What should the context provide as value?

  • Only the theme color
  • Only toggleTheme
  • Theme and toggleTheme function Correct answer
  • All CSS styles

Explanation: { theme, toggleTheme } gives both state and toggler.

2 toggleTheme

Question
function toggleTheme() {
  setTheme(theme === "light" ? "dark" : ____);
}
Answer
function toggleTheme() {
  setTheme(theme === "light" ? "dark" : "light");
}

Explanation: Dark becomes light, light becomes dark.

All lessons in Intermediate