[React] Hook ๐Ÿ‘‰ useContext

์Šน๋ฏธ๋‹ˆยท2021๋…„ 6์›” 19์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
5/10

1. useContext ๋ž€?

Context API์™€ ์œ ์‚ฌํ•œ context hook

const value = useContext(MyContext);

2. ํŠน์ง•

  • Consumer ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค.
  • useContext๋กœ ์ „๋‹ฌํ•œ ์ธ์ž๋Š” context ๊ฐ์ฒด ๊ทธ ์ž์ฒด์—ฌ์•ผ๋งŒ ํ•œ๋‹ค.
  • context ๊ฐ์ฒด(React.createContext์—์„œ ๋ฐ˜ํ™˜๋œ ๊ฐ’)์„ ๋ฐ›์•„ ๊ทธ context์˜ ํ˜„์žฌ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

3. ์‚ฌ์šฉ ์˜ˆ์‹œ

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}
profile
Web Frontend Developer

0๊ฐœ์˜ ๋Œ“๊ธ€