# Context Provider & Consumer in Class-based Component

## Context Provider & Consumer Practice

Context Provider & Consumer Practice example:

{% tabs %}
{% tab title="userContext.js" %}

```jsx
import React from "react"
// Creating context
const UserContext = React.createContext()
export default UserContext
```

{% endtab %}

{% tab title="Header.js" %}

```jsx
import React, {Component} from "react"
import UserContext from "./userContext"

class Header extends Component {
    render() {
        // Consuming context
        const user = this.context
        return (
            <header>
                <p>Welcome, {user}!</p>
            </header>
        )    
    }
}

// Defining contextType
Header.contextType = UserContext

export default Header

```

{% endtab %}

{% tab title="App.js" %}

```jsx
import React from "react"

import Header from "./Header"
import UserContext from "./userContext"

class App extends React.Component{
    // Defining contextType
    static contextType = UserContext
    
    render(){
        // Consuming context
        const user = this.context
        return (
            <div>
                <Header />
                <main>
                    <p className="main">No new notifications, {user}! 🎉</p>
                </main>
            </div>
        )
    }
    
}

export default App
```

{% endtab %}

{% tab title="index.js" %}

```jsx
/**
 * Challenge: Set up context to save the user's username and pass it to anywhere that is currently hardcoding "Username".
 * 
 * Use the static class property `contextType` on any components that need to consume context.
 */

import React from "react"
import ReactDOM from "react-dom"

import App from "./App"
import UserContext from "./userContext"

ReactDOM.render(
    // Passing props to Context Provider
    <UserContext.Provider value={"John"}>
        <App />
    </UserContext.Provider>, 
    document.getElementById("root")
)

```

{% endtab %}
{% endtabs %}
