Blog>
Snippets

Leveraging the New React Context

Illustrate the updated Context API with better performance and usability for passing data through component trees.
const ThemeContext = React.createContext('light');

// App component that provides the context
class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value='dark'>
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// Intermediate component that doesn't pass the theme down explicitly
function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

// Component that consumes the theme context
class ThemedButton extends React.Component {
  static contextType = ThemeContext;

  render() {
    return <button className={this.context}>I am styled by theme context!</button>;
  }
}
This code sets up a new React Context for theme, with 'light' as the default value. The 'App' component provides 'dark' as the current context value. 'Toolbar' component is a pass-through and does not handle the context itself. 'ThemedButton' consumes the 'ThemeContext' and applies the context (theme) to its className, which would need corresponding CSS rules.
.light {
  background-color: white;
  color: black;
}

.dark {
  background-color: black;
  color: white;
}
CSS rules for the light and dark themes. They change the background color and text color based on the current theme.
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>React Context Example</title>
  <script src='https://unpkg.com/react/umd/react.development.js'></script>
  <script src='https://unpkg.com/react-dom/umd/react-dom.development.js'></script>
</head>
<body>
  <div id='root'></div>
  <script src='app.js'></script>
</body>
</html>
HTML structure to run the React application. Includes React library from a CDN, targets a 'root' div to render the components, and links to the external 'app.js' file where the React components code would exist.