# useContext Hook

## `useContext` Hook

&#x20;`useContext()` is a simpler way to consume data from multiple contexts.

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

```jsx
import React, {useState} from "react"

// Create `context` which holds `provider` & `consumer`
const ThemeContext = React.createContext()

// Component that holds state and a toggle method
function ThemeContextProvider(props){
    // Set state
    const [theme, setTheme] = useState("dark")
    
    // Handle toggle
    function toggleTheme(){
        setTheme(prevTheme => prevTheme === "light" ? "dark" : "light" )
    }
    
    // Create a Context `Provider` that holds `prop` to be passed to `Consumer`
    return (
        <ThemeContext.Provider value={{theme:theme, toggleTheme:toggleTheme}}>
            {props.children}
        </ThemeContext.Provider>
    )
    
}

export {ThemeContextProvider, ThemeContext}

```

{% endtab %}

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

```jsx
import React, {useContext} from "react"
import {ThemeContext} from "./themeContext"

function Header(props) {
    // Passing `Provider` & `Consumer` via `ThemeContext` to `useContext`
    const context = useContext(ThemeContext)
    return (
        <header className={`${context.theme}-theme`}>
            <h2>{context.theme === "light" ? "Light" : "Dark"} Theme</h2>
        </header>
    )    
}

export default Header

```

{% endtab %}

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

```jsx
import React, {useContext} from "react"
import {ThemeContext} from "./themeContext"

function Button(props) {
     // Passing `Provider` & `Consumer` via `ThemeContext` to `useContext`
    const context = useContext(ThemeContext)
    return (
        <button onClick={context.toggleTheme} className={`${context.theme}-theme`}>Switch Theme</button>
    )    
}

export default Button

```

{% endtab %}

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

```jsx
import React from "react"

import Header from "./Header"
import Button from "./Button"

function App() {
    return (
        <div>
            <Header />
            <Button />
        </div>
    )
}

export default App
```

{% endtab %}

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

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

import App from "./App"
import {ThemeContextProvider} from "./themeContext"

ReactDOM.render(
    <ThemeContextProvider>
        <App />
    </ThemeContextProvider>, 
    document.getElementById("root")
)

```

{% endtab %}
{% endtabs %}
