# Context API | React JS

Recently React introduced some new cool fetures, one of interesting and much awaited feature is **New** **Context API**. New context API introduced with version 16.3. Context API’s are very useful in state management without props drilling. Let’s deep dive into the same.

**Problem**

In many cases, in our application we need to pass the state of componenet to two-three level deep. so we passed props down to the levels and levels of the component tree when not all of those components necessarily need those props. Suppose component hierarchy is complex then state management would be overhead for developers.

**Solution**

For state management theres are couple of libraries available like Redux (most used and trending). But React introduced the Context API to solve the problem of props drilling and made developers work of state management simple.

**When to use Context**

As React suggests “If you only want to avoid passing some props through many levels. Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.”

**How to use Context**

So now if you want to use context in your application, first create context object.

```
import { createContext } from 'react';
```

```
const {Provider, Consumer } = React.createContext();
```

Then create a wrapper component that will return Provider component and also add as children all the components from which you want to access the context.

```
class ProviderComponent extends Component {
    state = {
        title : “Vishal”,
    }
```

```
render() {
        return ( 
        <Provider value={this.state}>
          <Website />
        </Provider>
        )
    }
}
```

Our Website component look like

```
const Website = () => (
  <div>
    <Header />
    <Footer />
  </div>
)
```

Now if we want to access the title from provider component to the Header componet, we can simply consume state of provider component using context without prop drilling.

```
const Header = () => (
  <div>
     <Consumer>
        {(context) => context.title}
      </Consumer>
  </div>
)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tkssharma.gitbook.io/react-training/day-07/context-api-or-react-js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
