useContext Hook

Learn the "useContext" hook by building a basic application with it.

What is it?

useContext provides the current context value of the context object passed to it. The useContext hook relies on nearest Context Provider to determine the current value for that context.

Firstly, take a look at an example implementation using class and later convert it to use the useContext hook.

Assume you have an application with different theme colors depending upon the brand definition.

import React, { Component, createContext } from 'react';
const ThemeContext = createContext('green');

const App = () => {
  return (
    <ThemeContext.Provider value={'green'}>
      <Content />
    </ThemeContext.Provider>
  );
};

class Content extends Component {
  static contextType = ThemeContext;

  render() {
    return <Button theme={this.context} />;
  }
}

export default App;

First, create a context object ThemeContext using createContext method from React library. ThemeContext has the default theme value as green.

Later, wrap the app with ThemeContext.Provider as well as specify the theme value. After this, other components can access the value of the theme by using ThemeContext. In this example, a theme prop on a Button component is provided. The value of this theme is taken directly from React Context.

Look at how you can convert the same example to use the useContext hook.

The ThemeContext creation and App is exactly the same as the code snippet below. The difference is in the Content component. Instead of using a static variable in the class, simply call useContext to return the current value of ThemeContext.

import React, { createContext, useContext } from 'react';
const ThemeContext = createContext('green');

const App = () => {
  return (
    <ThemeContext.Provider value={'green'}>
      <Content />
    </ThemeContext.Provider>
  );
};

const Content = () => {
  const theme = useContext(ThemeContext);
  return <Button theme={theme} />;
};

When do we use it?

Wherever a React Context API is being used, the useContext hook is used to retrieve the value of a given context.

Syntax

useContext accepts a React Context object as the only input.

The output of useContext is the current value of the provided context.

const value = useContext(MyThemeContext);

As mentioned earlier, this value is determined by the nearest Context Provider. If the value of Provider changes, useContext hook will trigger a re-render in the calling component.

NOTE

If a parent component uses memoization to skip renders, the useContext hook will still cause a re-render in a component where it was called in case context value changes.

Get hands-on with 1400+ tech skills courses.