---
# System prepended metadata

title: React  hook 之 useContext
tags: [開發經驗分享]

---

# React  hook 之 useContext
> useContext is a React Hook that lets you read and subscribe to context from your component.

深層子組件取用母組件更新後的值

## 官方範例
```jsx
import { createContext, useContext } from 'react';

const ThemeContext = createContext(null);

export default function MyApp() {
  return (
    <ThemeContext.Provider value="dark">
      <Form />
    </ThemeContext.Provider>
  )
}

function Form() {
  return (
    <Panel title="Welcome">
      <Button>Sign up</Button>
      <Button>Log in</Button>
    </Panel>
  );
}

function Panel({ title, children }) {
  const theme = useContext(ThemeContext);
  const className = 'panel-' + theme;
  return (
    <section className={className}>
      <h1>{title}</h1>
      {children}
    </section>
  )
}

function Button({ children }) {
  const theme = useContext(ThemeContext);
  const className = 'button-' + theme;
  return (
    <button className={className}>
      {children}
    </button>
  );
}
```
## 適合情境
多個子元件共用不常更新的母值

## ref
[useContext](https://react.dev/reference/react/useContext#usage)