Register to get access to free programming courses with interactive exercises

useContext Hook JS: React Hooks

In React, we pass data from upper to lower levels. But this approach is inconvenient when we work with global data that is needed simultaneously in many components at different levels of the hierarchy.

Such data includes the current level or color scheme. It is not convenient to transfer such data directly; you have to drag it through the entire application. We can use a context mechanism to deal with it. It allows us to pass things to the application and get access to data directly in any component, bypassing props.

The useContext() hook allows you to use contexts inside the component. To do this, you need to perform three steps:

  1. Initialize the context object in the same place where we initialized the application:

    // We pass the default value by the parameter
    // We have chosen the context object's name arbitrarily
    const UserContext = React.createContext({});
  2. Connect the provider and pass the data to the context object via the value prop:

    // user is the data inside the context
    <UserContext.Provider value={user}>
      <MyComponent />
  3. Get the context object data:

    import React, { useContext } from 'react';
    const MyComponent = () => {
      // Returns the entire context object
      const user = useContext(UserContext);
      return <h1>{}</h1>;

Here is another example of a context object. We store the current topic in it:

const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  dark: {
    foreground: '#ffffff',
    background: '#222222',

const ThemeContext = React.createContext(
  themes.dark, // default value

And somewhere inside the application:

<ThemeContext.Provider value={/* current topic */}>
  <Content />

We can store both a primitive value and an object inside the context. React does not track changing the contents of this object and therefore doesn't trigger re-rendering.

But if you replace the object itself, React will know about the change because of the changed link and will redraw the components inside the provider.

Sometimes, we store dynamic data in the context — during authorization, for example. When the user logs in, we have to save some data to provide the user with additional functions.

The context doesn't provide anything for this, but you can pass methods for manipulating data to the context and store it using useState().

A more advanced option is to create a provider in a separate component. This way, we can isolate the data from the entire application and transfer the interface to the components to interact with the data.

To do this, create a context in a separate module so that all components can import it:

// ThemeContext.js

import { createContext } from 'react';

export default createContext({
  themes: {},
  theme: {},
  setTheme: () => {},

Creating a separate provider component:

import ThemeContext from './ThemeContext.js';

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState(themes.dark);

  const setLightTheme = () => setTheme(themes.light);

  const setDarkTheme = () => setTheme(themes.dark);

  return (
    <ThemeContext.Provider value={{ theme, setLightTheme, setDarkTheme, themes }}>

And inside the application, we use the provider as a regular component:

  <MyComponent />

In the component itself, you can now import the context object and use functions from the provider to change the state in the context:

import React, { useContext } from 'react';
import ThemeContext from './ThemeContext.js';

const MyComponent = () => {
  const { setLightTheme } = useContext(ThemeContext);

  return <button onClick={() => setLightTheme()}>Activate light mode</button>;

Context is a convenient mechanism for certain situations, but it shouldn't become the default way to pass data around the application. This temptation appears for many who are using it for the first time. The main problem with context objects is that they bind components to global data, making it difficult to reuse them in other situations.

Recommended materials

  1. Context mechanism
  2. Using the Context Hook

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
hours of theory

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.