# Context Provider & Consumer in Function-based Component

## Context Provider & Consumer Example

Context Provider & Consumer Practice:

{% 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 from "react"
import UserContext from "./userContext"

function Header() {
    return (
        <header>
            // Consuming context
            <UserContext.Consumer>
                {username => (
                    <p>Welcome, {username}!</p>
                )}
            </UserContext.Consumer>
        </header>
    )
}

export default Header

```

{% endtab %}

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

```jsx
import React from "react"

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

function App() {
    return (
        <div>
            <Header />
            <main>
                // Consuming context
                <UserContext.Consumer>
                    {username => (
                        <p className="main">No new notifications, {username}! 🎉</p>
                    )}
                </UserContext.Consumer>
            </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.
 * https://reactjs.org/docs/context.html
 */

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

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

ReactDOM.render(
    // Providing context
    <UserContext.Provider value={"bob123"}>
        <App />
    </UserContext.Provider>, 
    document.getElementById("root")
)

```

{% endtab %}
{% endtabs %}
