# useContext

## useContext

The `useContext` hook helps components share data with each other.

It is very common to have:

1. a nested tree of components
2. a need for components to share data across branches of the tree

In such scenarios we would lift state up to a common parent and pass the data down as props. With a deeply nested component tree however, this results in having to pass the prop through multiple layers of components even if those layers don't need that prop at all. The `useContext` hook gives us an alternative to this "prop drilling". It creates a direct portal between the component that **provides** the state (**context**) and the components that need to **consume** that state.

```jsx
import { useState, useContext, createContext } from "react";

const CartContext = createContext([]);

const App = () => {
  const [cartItems, setCartItems] = useState([])

  return (
    <CartContext.Provider value={cartItems}>
      <NavBar />
      <Checkout />
    </CartContext.Provider>
  );
};

const NavBar = () => {
  const { cartItems } = useContext(CartContext)
  return (
    <p>{cartItems.length}</p>
  );
}

const Checkout = () => {
  const { cartItems } = useContext(CartContext)
  return (
    <ul>
      {cartItems.map(item) => (<li>{item.title}</li>)}
    </ul>
  )
}
```

#### References

* <https://react.dev/learn/passing-data-deeply-with-context>
* <https://react.dev/reference/react/createContext>
