Search⌘ K

Consuming a context in a strongly-typed class component

Explore how to consume React context within class components using TypeScript to ensure strong typing. Learn to use static contextType and the Consumer component to access context with type safety, enhancing code readability and reducing errors in React applications.

Trying to use the context hook in a class component #

We are going to continue using the context we created in the last lesson that allows consumers to share and set a theme. Let’s update the Header component to be a class component:

class Header extends React.Component {
  render() {
    const { theme, setTheme } = useTheme()!;

    return (
      <div style={{ backgroundColor: theme }}>
        <select
          value={theme}
          onChange={e => setTheme(e.currentTarget.value)}
        >
          <option value="white">White</option>
          <option value="lightblue">Blue</option>
          <option value="lightgreen">Green</option>
        </select>
        <span>Hello!</span>
      </div>
    );
  }
}

Can you spot a problem with this implementation?

Using the context

...