Register to get access to free programming courses with interactive exercises

useContext Hook JS: React Hooks

In React, data is transferred inside the components via passes from the upper levels to the lower ones. But sometimes this approach is inconvenient when working with global data that's needed simultaneously in many components at different levels of the hierarchy. Such data includes the current level, or the current theme (dark or light, etc.). It isn't convenient to transfer such data directly; you'll have to drag them through the entire application. To deal with this, a context mechanism has been added to React. It allows you to pass things to the application and get access to data directly inside 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 the application is initialized

    // The default value is passed by the parameter
    // The context object's name is chosen 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 />
    </UserContext.Provider>
    
  3. Get the context object's data

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

Here is another example of a context object in which the current topic is stored:

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 />
</ThemeContext.Provider>

Both a primitive value and an object can be stored inside the context. Changing the contents of this object isn't tracked by React in any way, and therefore doesn't lead to re-rendering. But if you replace the object itself, then React will know about the change because of the change to the link, and will redraw the components inside the provider.

Sometimes, you can have situations where dynamic data needs to be stored in the context. For example, during authorization. When the user is logged in, we have to save some data so that the user is provided with additional functions. The context itself doesn't provide anything for this, but you can pass methods for manipulating data to the context, and store the data itself 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 }}>
      {children}
    </ThemeContext.Provider>
  );
};

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

<ThemeProvider>
  <MyComponent />
</ThemeProvider>

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 specific situations, but it shouldn't become the main way to pass data inside the application. This temptation appears to many using it for the first time. The main problem with context objects is the binding of components to global data, and this makes it difficult to reuse them in other situations.


Recommended materials

  1. Using the Context Hook
  2. Context mechanism

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
130
courses
1000
exercises
2000+
hours of theory
3200
tests

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: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

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.