---
# System prepended metadata

title: "\U0001F3C5 Day 12｜React Hook - useContext"
tags: [2022 React 新手讀書會]

---

---
 tags: 2022 React 新手讀書會
---
# 🏅 Day 12｜React Hook - useContext
在前面我們學到了父子元件運用 props 來傳遞資料，那當元件有兩層以上，或是同一層的子元件要互相傳遞狀態，使用 props 就相對於不那麼適合了，因此今天要來介紹 useContext 這個 hook。

## useContext
假設我們今天使用同一主題的顏色，並讓每個元件都能取得到同一組主題色系，那就可以使用 useContext 將定義好的 theme 資料傳遞到其他元件，不需要透過 props 傳入。
```jsx=
const value = useContext(MyContext);
```
useContext 接收的是一個 context 物件，這個 context 物件是來自 React.createContext 的回傳值。而這個值會透過距離元件最近的 `<MyContext.Provider>` 來傳入。

所以這邊要先定義 MyContext，舉例：
```jsx=
const MyContext = React.createContext();
```
`MyContext.Provider` 建立：透過 Provider 把 value 傳入，其他元件就能夠用 useContext 來取得到 `theme.light` 值囉
```jsx=
function ThemeText() {
  const theme = React.useContext(MyContext);
  return (
    <button style={{ color: theme.background }}>
      我是 theme 中的 light background 色的文字
    </button>
  );
}
function ThemeButton() {
  const theme = React.useContext(MyContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      我是 theme 中的 light 按鈕
    </button>
  );
}

function App() {
  const themes = {
    light: {
      foreground: "#ffffff",
      background: "#313675"
    }
  };
  return (
    <MyContext.Provider value={themes.light}>
      <ThemeButton />
        <ThemeText />
    </MyContext.Provider>
  );
}
```
[完整 Demo](https://codepen.io/hexschool/pen/NWYvbrX)

[文件參考](https://zh-hant.reactjs.org/docs/hooks-reference.html#usecontext)

## 題目
請複製 （右下角 fork）這個[範例](https://codepen.io/hexschool/pen/xxWLEBB)，並加入 useContext 使 BlueComponent 和 RedComponent 取得 user 資料，顯示畫面如下：
![](https://i.imgur.com/7LKGIEL.png)



## 回報流程
將答案寫在 CodePen 並複製 CodePen 連結貼至底下回報就算完成了喔!
解答位置請參考下圖（需打開程式碼的部分觀看）
![](https://i.imgur.com/vftL5i0.png)

<!-- 解答： 
```
// 練習：定義 createContext
const UserContext = React.createContext();
function BlueComponent () {
  // 練習：使用 useContext 取得 User 資料
  const user = React.useContext(UserContext);
  return <p style={{ color: 'blue' }}> {user}</p>
}
function RedComponent () {
  // 練習：使用 useContext 取得 User 資料
  const user = React.useContext(UserContext);
  return <p style={{ color: 'red' }}> {user}</p>
}
function Example() {
  const [user, setUser] = React.useState("Nick");
  // 練習：使用 useContext.Provider 傳遞 user 資料
  return <UserContext.Provider value={user}>
    <BlueComponent />
    <RedComponent />
  </UserContext.Provider>;
}
```
-->


回報區
---


|   Discord    |                    CodePen / 答案                      |
|:----------:|:-------------------------------------------------------:|
| Rice#8043 |         [CodePen](https://codepen.io/riecball/pen/BardOOz?editors=0010)         |
| yunyun#5215 |[CodePen](https://codepen.io/yun_yunni/pen/GRxwoPV)|
| 真．穎旻粉撕#4995 |[CodePen](https://codepen.io/gbnbihif/pen/NWYExoN) |
| Eric Su#7798 |[CodePen](https://codepen.io/wc-su/pen/eYMQJQG)|
|     DIANAxAKKO#4298     |   [Codepen](https://codepen.io/redfire29/pen/yLKQewb)    |
| Vita Ora#4585     |   [Codepen](https://codepen.io/showlovezz/pen/MWVzKzm?editors=0010)    |
| 棒腿#9350 |[Codepen](https://codepen.io/frankHsu/pen/MWVzKZo?editors=1010)|
| 布魯諾#7239 |[Codepen](https://codepen.io/bruno-yu/pen/KKorVEa?editors=1010)|
| Ayre#0016|[Codepen](https://codepen.io/yichunlin09/pen/MWVzKxo?editors=0010)|
| 魚魚#0937|[Codepen](https://codepen.io/fish0522/pen/PoRxZgw)|
|niel#2413|[Codepen](https://codepen.io/danielhsu/pen/mdxQPbb)|
|rainbow#3329|[Codepen](https://codepen.io/g901612002/pen/QWmJNbp)|
|huch09#1426|[Codepen](https://codepen.io/subarashii-huch09/pen/dymQMYE?editors=1010)|
|kimi#2092|[Codepen](https://codepen.io/a3216lucy/pen/YzaRwgM)|
|HedgehogKU|[CodePen](https://codepen.io/hedgehogkucc/pen/VwXVamo?editors=1010)|
|AllenW#1132|[CodePen](https://codepen.io/AllenW/pen/oNqQbOJ?editors=1011)|
|Shau#6400|[CodePen](https://codepen.io/shau-chen/pen/jOzQqLa)|
|彼得#1923|[Codepen](https://codepen.io/shiou-ho/pen/JjLeXEz)|
|yoshidc#0455|[Codepen](https://codepen.io/yoshiyyc/pen/oNqQxwK)|
|Arista#5802|[Codepen](https://codepen.io/arista-hsieh/pen/MWVzyzq)|
|Wu#0167|[Codepen](https://codepen.io/Xander0705/pen/ExEOKMB)|
|hw#0715|[Codepen](https://codepen.io/Lhwei/pen/abYQNNR)|
|Yiling#4054|[Codepen](https://codepen.io/lin010/pen/yLKQJBQ?editors=1010)|
|許揚民 Evan#4546|[Codepen](https://codepen.io/gitevanhsu/pen/bGvQeGL?editors=0011)|
|SHIN#6075|[Codepen](https://codepen.io/shin9626/pen/rNdQLBb)|
| 黃士桓#7654 | [codePen](https://codepen.io/shr-huan-huang/pen/PoRxzwJ) |
| L0F0#8733| [codePen](https://codepen.io/l0f0/pen/poLQbzx?editors=0010) |
| yuyu#6310| [codePen](https://codepen.io/yuyu0905/pen/JjLeKEG?editors=0010) |
| wiimax#4564| [codepen](https://codepen.io/willismax/pen/qBoQNjN)
| hiYifang #0736| [codepen](https://codepen.io/hiYifang/pen/bGvQeox)
| 威爾#1694 | [CodePen](https://codepen.io/WILL_Wu/pen/yLKQJXr) |
| LEO#7779 | [CodePen](https://codepen.io/nekorice/pen/MWVzeON) |
| ChloeLo#4858 | [CodePen](https://codepen.io/chloelo/pen/gOeQMOR) |
| VadaChen#2055 |[CodePen](https://codepen.io/vadachen/pen/KKorMLP?editors=0010)|
| Yanyan#3555|[Codepen](https://codepen.io/wei-yi-lee/pen/QWmJEPX?editors=1010)|
|雪莉#4827|[Codepen](https://codepen.io/utshang216/pen/jOzQrog)|
| Dylan_Lin#7320 |[Codepen](https://codepen.io/lin-dylan/pen/qBoQNqZ?editors=1010)|
| 無名#6427 |[Codepen](https://codepen.io/Nomoney/pen/YzaRGYR?editors=0010)|
|Tsuei#9284|[CodePen](https://codepen.io/AlbertoLL/pen/poLQEGe)|
|𝓛𝓊𝒸𝓎#8635|[CodePen](https://codepen.io/lucygirl/pen/xxWQRby)|
Robert Lo#9653|[CodePen](https://codepen.io/Robert-Lo/pen/ZExmBpx)|
| JarDar#6980         | [codepen](https://codepen.io/jardarpen/pen/xxWQREm)                  |
| ------------------- | -------------------------------------------------------------------- |
| LinaChen#1796       | [codepen](https://codepen.io/LinaChen/pen/BarGQZQ)                   |
| Bumble幫啵#0255     | [codepen](https://codepen.io/pen/wvmQoeg)                            |
| Chelly#6129         | [codepen](https://codepen.io/chellyhsu/pen/zYWMBGg)                  |
| EvaLin#4546         | [Codepen](https://codepen.io/evalin0316/pen/YzaRpOy?editors=1010)    |
| Evonne#7078         | [CodePen](https://codepen.io/Hsu1Fang/pen/GRxwrJE?editors=1011)      |
| wenyun#2362         | [CodePen](https://codepen.io/wenyuncc/pen/dymQNGX?editors=1010)      |
| JC#8658             | [Codepen](https://codepen.io/jcsamoyed/pen/JjLeEyX)                  |
| IceSam#7836         | [Codepen](https://codepen.io/sam-hsu/pen/RwMqKWp)                    |
| RON#2813            | [Codepen](https://codepen.io/Ron115/pen/eYMQBXb)                     |
| YJ#1839             | [Codepen](https://codepen.io/cshjufxc/pen/MWVzpJe?editors=1010)      |
| Midnightdinner#6220 | [Codepen](https://codepen.io/woowooyong/pen/RwMqpeO)                 |
| Mr.Sean#3825        | [Codepen](https://codepen.io/sean_1215/pen/yLKQemo)                  |
| Zengapp.listenZeng  | [Codepen](https://codepen.io/tyzyoko/pen/vYRQmXB)                    |
| Timothy#5863        | [Codepen](https://codepen.io/timothy_hippo/pen/ZExmKvR?editors=0011) |
| IreneLee#7932       | [Codepen](https://codepen.io/ntjtcxpt-the-animator/pen/ZExmyag)      |
| easton#3863         | [Codepen](https://codepen.io/EastonIsCodingNow/pen/dymQzKq)          |
| 城堡#2126           | [Codepen](https://codepen.io/tthcastle/pen/LYdXzNq)                  |
| Stanley#2505        | [Codepen](https://codepen.io/bigbearada/pen/poLQdzO)                 |
| TedWang             | [Codepen](https://codepen.io/wangtaiyan/pen/XWEyzrQ?editors=0010)    |
| Neal#0665           | [Codepen](https://codepen.io/neallkf/pen/qBoQqvB?editors=1011)       |
| Ryder#7398          | [Codepen](https://codepen.io/rider159159/pen/WNzYXGK)                |
| lingxuan            | [Codepen](https://codepen.io/lingxuan0618/pen/QWmJOMJ)               |
| 山貓(焜)#7041       | [Codepen](https://codepen.io/nopeta/pen/bGvQYOO)                     |
| Claire#2116         | [Codepen](https://codepen.io/claire-chang-the-bashful/pen/NWYEwZJ)   |
| Kelvin#3296         | [Codepen](https://codepen.io/kelvinchang/pen/JjLeMdJ)                |
| Kenge#3690          | [Codepen](https://codepen.io/pgkusn/pen/JjLeMKy)                     |
| Rocker#6235         | [Codepen](https://codepen.io/RockerLi/pen/JjLeOvR)                   |
| aki                 | [codepen](https://codepen.io/aki168/pen/ZExmJMK)                     |
| 楓之聲#6945         | [Codepen](https://codepen.io/sshane258/pen/PoRxQVp)                  |
| shin#5792           | [Codepen](https://codepen.io/hah1030/pen/mdxQXaE)                    |
| Carolkiki2003#7399  | [Codepen](https://codepen.io/wasfzuig/pen/OJvavBw)                   |
| kyle890721#1016     | [Codepen](https://codepen.io/KYLE890721/pen/MWVzGPp)                 |
| Anson#3594          | [Codepen](https://codepen.io/huanmingchang/pen/WNzYapp?editors=1010) |
| Joechiboo#3960      | [Codepen](https://codepen.io/joe-chiboo/pen/qBoQJJz)                 |
| Mitour#0672         | [CodePen](https://codepen.io/mitour/pen/yLKQQKr)                     |
|aka 又杰寶貝我婆|[codepan](https://codepen.io/wei-nie/pen/RwMqEQq?editors=1011)|
|葉秋#2335|[codepan](https://codepen.io/as880074/pen/dymQvEa)|
|ZengZeng|[codepan](https://codepen.io/tyzyoko/pen/vYRQmXB)|
| Mao#5230 |[codepan](https://codepen.io/taomaomao/pen/NWYEVxr?editors=0010)|
| KuoMin#4931 |[codepan](https://codepen.io/KuoMin/pen/OJvaebx?editors=1010)|
| NinaKuo#3332 |[Codepen](https://codepen.io/ninakuo0814/pen/eYMxqGY)|
| Otis#8455 |[Codepen](https://codepen.io/humming74/pen/oNqVNyg?editors=1111)|
|minmin#8960|[codePen](https://codepen.io/minfan-chen/pen/ExEMvma)|
|hahaalin#3209|[codePen](https://codepen.io/shellyPen/pen/jOzdNbq)|
|Mori#5582|[codePen](https://codepen.io/flower9312/pen/ExEMrWm)|
|Ada|[codePen](https://codepen.io/zggsoagv-the-scripter/pen/gOeZojq)|
|larahuang#8309|[codePen](https://codepen.io/lara1105huang/pen/poLBOgV)|
|hobby#6565|[codePen](https://codepen.io/hobbyling/pen/oNqRjbM)|
|eching#9183|[codePen](https://codepen.io/echin/pen/WNzBMGY?editors=0010)|
|喬喬#2824|[codePen](https://codepen.io/joanne-wei/pen/oNqreJg?editors=0010)|
|Overy#4545|[Codepen](https://codepen.io/overy-tsai/pen/PoRrJzO)|
|Eileen#6454|[Codepen](https://codepen.io/Eileen-io/pen/LYdKNWR)|
|JimHwang#3594|[Codepen](https://codepen.io/jimh1129/pen/poLMoKy)|
|JimmyChang#5558|[Codepen](https://codepen.io/JimmyChangWenChi/pen/qBoGJBb?editors=1010)
|Kyle Lin#0561|[Codepen](https://codepen.io/thenkyle/pen/vYjYGbK)|
|C#4593|[Codepen](https://codepen.io/ShaniMa/pen/PoeGOvr)|
|GL#2256|[Codepen](https://codepen.io/4genie/pen/eYjKpbj)|
| Nico#8739         | [CodePen](https://codepen.io/Nicof2e/pen/gOQwprM)                     |
|Eshiunm|[CodePen](https://codepen.io/Code-My/pen/poBOGNe)|
