Preview:
import React, { useContext, createContext } from 'react';

// Step 1: Create a context with createContext()
const ThemeContext = createContext();

// Step 2: Create a ThemedComponent to consume the theme value
function ThemedComponent() {
  // Step 3: Use useContext hook to consume the theme value from the context
  const theme = useContext(ThemeContext);

  return (
    <div style={{ backgroundColor: theme.background, color: theme.text }}>
      <h2>Themed Component</h2>
      <p>This component consumes the theme value from the context.</p>
    </div>
  );
}

// Step 4: Wrap the ThemedComponent with ThemeContext.Provider in the App component
function App() {
  const themeValue = {
    background: 'lightblue',
    text: 'black'
  };

  return (
    <div>
      <h1>App Component</h1>
      {/* Provide the value of the theme */}
      <ThemeContext.Provider value={themeValue}>
        {/* ThemedComponent is wrapped with ThemeContext.Provider */}
        <ThemedComponent />
      </ThemeContext.Provider>
    </div>
  );
}

export default App;
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter