React Foundations·Practice drills 5

Drill 12: Compare — Context and shared state

Compare this example with a related lesson or language.

Intermediate 5 min read Lesson 124 of 300 Challenge included
What you will be able to do
  • Compare this example with a related lesson or language.

Practice task

Compare this example with a related lesson or language.

ThemeContext.tsxTSX
import { createContext, useContext, useState, type ReactNode } from 'react'

type Theme = 'light' | 'dark'

type ThemeContextValue = {
  theme: Theme
  toggle: () => void
}

const ThemeContext = createContext<ThemeContextValue | null>(null)

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light')

  function toggle() {
    setTheme((current) => (current === 'light' ? 'dark' : 'light'))
  }

  return <ThemeContext.Provider value={{ theme, toggle }}>{children}</ThemeContext.Provider>
}

export function useTheme(): ThemeContextValue {
  const value = useContext(ThemeContext)
  if (value === null) {
    throw new Error('useTheme must be used within a ThemeProvider')
  }
  return value
}
Your turn

Write your answer

Easy

Compare this example with a related lesson or language.

TEXT · starter
Your answer…
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 124 of 300 · 0% of course