Register to get access to free programming courses with interactive exercises

Context API JS: React

Passing data down the component hierarchy via props is a wordy but straightforward mechanism. You can always see where the data came from and how it got in, and the components are easy to reuse because they depend only on the input data. But there are situations where passing props doesn't match how the code works.

Let's take a hypothetical current user as an example. Often, user data is needed in different parts of the page and deep components simultaneously. To do this, you should pass the user all over the hierarchy, even where the component doesn't need it.

The only purpose of such a transfer is to send the data to its destination, passing all the intermediate components along the way.

It turns out that many components do not use the user in any way. They only pass them on down the chain. The user's data, in our situation, are global. Several components at different levels of the hierarchy need them at once. There is, however, a workaround for such tasks in React.

The Context API is a mechanism for making global data available from any component directly, without props. Its use boils down to three steps:

  1. Creating the context:

    // We pass a default value to the parameter
    // We pass an empty object because there's no user yet, but there will be one (and it will be an object)
    // The context can only store one value
    // We chose the context name based on what data are stored inside
    const UserContext = React.createContext({});
    
  2. Transferring data into the context. We wrap the required components in a context component <UserContext.Provider> and pass the required data there in the value prop:

    // The context will only be available inside the components it wraps
    // currentUser - the current user's data
    <UserContext.Provider value={currentUser}>
      <App />
    </UserContext.Provider>
    
  3. Getting data from the context in the right place:

    import UserContext from '...';
    
    // Any component inside the <UserContext.Provider>
    class InnerComponent extends React.Component {
    
      // Defining the type of context
      static contextType = UserContext;
      render() {
        // Accessing the context through this.context
        return <Profile user={this.context} />;
      }
    }
    

Unlike props, changing the data in the context does not result in a redraw by default. It's ideal when the data in the context is read-only. It's better to store modifiable data inside component states. However, if you need to, it is possible to respond to a change of context. You can read more about this in the documentation.

Programmers rarely use this feature in application code but write various libraries with it.


Recommended materials

  1. Context API

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

The Hexlet support team or other students will answer you.

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:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
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.