beecomci / today_i_learned

0 stars 0 forks source link

[React-Basic-Hooks] 10. Context #15

Open beecomci opened 3 years ago

beecomci commented 3 years ago

Context

React에서 data는 top-down(parent to child)로 흐른다. Virtual DOM 자체가 트리 형태 앱 전체에서 여러군데에서 사용되는 값(global value)을 상위에서 전달하는 방법

usage

Context.Provider에 값 변경이 있을 때 useContext(Context) 사용한 모든 component는 re-render 발생

Context를 너무 빈번하게 사용하면 re-render가 자주 일어나기 때문에 최적화가 필요한데 최적화를 직접 적용하기 보다는 Redux or Mobx 사용 Global 하게 사용할 수 있는 곳에서 Context를 활용하는게 좋음

@09-context

// AS-IS
function App() {
  return <Toolbar theme="green" />;
}

// 내부에서 전혀 theme를 사용하지 않고 있음 
// ThemedButton을 위해 단순 전달
function Toolbar({ theme }) {
  // The Toolbar component must take an extra "theme" prop
  // and pass it to the ThemedButton. This can become painful
  // if every single button in the app needs to know the theme
  // because it would have to be passed through all components.
  return (
    <div>
      <ThemedButton theme={theme} />
    </div>
  );
}

const ThemedButton = ({ theme }) => (
  <button className={`button-${theme}`}>
    button
  </button>
)

export default App;
// TO-BE
import { createContext, useContext } from 'react';

// green으로 초기화
const ThemeContext = createContext('green');

const useThemeContext = () => {
  const theme = useContext(ThemeContext) // value 값
  return theme
}

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

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

const ThemedButton = () => {
  const theme = useThemeContext()
  return (
    <button className={`button-${theme}`}>
      button
    </button>
  )
}

export default App;