[React] Context API

✨ 강은비·2022λ…„ 1μ›” 15일
0

React

λͺ©λ‘ 보기
19/36

react μŠ€ν„°λ””μ—μ„œ λ¦¬μ•‘νŠΈλ₯Ό λ‹€λ£¨λŠ” κΈ°μˆ μ΄λΌλŠ” 책을 μ„ μ •ν–ˆκ³  이 책을 읽고 배운 것을 λ°”νƒ•μœΌλ‘œ μž‘μ„±λ˜μ—ˆλ‹€.


🌐 Context APIλž€?

πŸ’‘ μ „μ—­μ μœΌλ‘œ μ‚¬μš©λ˜λŠ” 데이터λ₯Ό 관리할 λ•Œ μœ μš©ν•˜κ²Œ μ‚¬μš©λ˜λŠ” κΈ°λŠ₯

  • μ‚¬μš©μž 둜그인 정보, ν™˜κ²½ μ„€μ •, ν…Œλ§ˆ λ“± μ „μ—­μ μœΌλ‘œ ν•„μš”ν•œ 데이터가 μžˆμ„ λ•ŒλŠ” 주둜 μ΅œμƒμœ„ μ»΄ν¬λ„ŒνŠΈμΈ App의 state에 λ„£μ–΄μ„œ κ΄€λ¦¬ν•œλ‹€.
  • 이후 νŠΉμ • μ»΄ν¬λ„ŒνŠΈμ—μ„œ 데이터λ₯Ό ν•„μš”λ‘œ ν•  λ•Œ μ΅œμƒμœ„ μ»΄ν¬λ„ŒνŠΈμ—μ„œ μ—¬λŸ¬ μ»΄ν¬λ„ŒνŠΈλ₯Ό 거쳐 props둜 μ›ν•˜λŠ” μƒνƒœλ₯Ό μ „λ‹¬ν–ˆλ‹€.
  • ν•˜μ§€λ§Œ Context APIλ₯Ό μ‚¬μš©ν•˜λ©΄ 단 ν•œ λ²ˆμ— μ›ν•˜λŠ” 값을 받아와 μ‚¬μš©ν•  수 μžˆλ‹€.

πŸ“ Context API μ‚¬μš©λ²•

Context 객체 λ§Œλ“€κΈ°

  • Context 객체λ₯Ό λ§Œλ“€ λ•ŒλŠ” createContext ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•œλ‹€.
  • 인자둜 ν•΄λ‹Ή Context의 기본값을 μ „λ‹¬ν•œλ‹€.
  • 이 기본값은 Provider μ»΄ν¬λ„ŒνŠΈλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šμ•˜μ„ λ•Œλ§Œ μ‚¬μš©λœλ‹€.
const MyContext = createContext(defaultValue);

Provider

  • Provider λ₯Ό μ΄μš©ν•˜μ—¬ context 값을 λ°”κΏ€ 수 μžˆλ‹€.
  • Provider μ»΄ν¬λ„ŒνŠΈλŠ” value props을 λ°›μ•„μ„œ 이 값을 ν•˜μœ„μ— μžˆλŠ” μ»΄ν¬λ„ŒνŠΈλ“€μ—κ²Œ μ „λ‹¬ν•œλ‹€.
  • Context에 μžˆλŠ” 값이 ν•„μš”ν•œ μ»΄ν¬λ„ŒνŠΈλ“€μ„ Provider μ»΄ν¬λ„ŒνŠΈλ‘œ 감싼닀.
  • Provider ν•˜μœ„μ— 또 λ‹€λ₯Έ Provider μ»΄ν¬λ„ŒνŠΈκ°€ μžˆλŠ” 것이 κ°€λŠ₯ν•˜λ©°, 이 경우 ν•˜μœ„ Provider의 valueκ°€ μš°μ„ μ‹œλœλ‹€.
  • Context.Provider의 value props 값이 λ°”λ€” λ•Œλ§ˆλ‹€ Contextλ₯Ό μ‚¬μš©ν•˜λŠ” ν•˜μœ„ μ»΄ν¬λ„ŒνŠΈλ“€μ΄ λ¦¬λ Œλ”λ§λœλ‹€.
    • λ§Œμ•½ value props μ•ˆμ— μ—¬λŸ¬ 값듀이 μžˆλ‹€κ³  κ°€μ •ν•  λ•Œ μ»΄ν¬λ„ŒνŠΈκ°€ Contextμ—μ„œ νŠΉμ • 값에 μ˜μ‘΄ν•  경우, ν•΄λ‹Ή κ°’ 말고 λ‹€λ₯Έ 값이 변경될 λ•Œλ„ μ»΄ν¬λ„ŒνŠΈκ°€ λ¦¬λ Œλ”λ§λœλ‹€.
    • πŸ’‘ λΆˆν•„μš”ν•œ λ¦¬λ Œλ”λ§μ΄ λ°œμƒν•˜μ§€ μ•ŠκΈ° μœ„ν•΄ 관심사에 맞게 Contextλ₯Ό λΆ„λ¦¬ν•˜μ—¬ μƒμ„±ν•œλ‹€. (ex. StateContext / ActionContext)
<MyContext.Provider value={/* μ–΄λ–€ κ°’ */}></MyContext.Provider>

Consumer

  • Context에 μžˆλŠ” 값을 Context.Consumerλ₯Ό μ΄μš©ν•΄ μ‘°νšŒν•  수 μžˆλ‹€.
  • Context.Consumer의 μžμ‹μ€ ν•¨μˆ˜μ—¬μ•Ό ν•œλ‹€.
  • 이 ν•¨μˆ˜λŠ” Context의 ν˜„μž¬ 값을 λ°›κ³  React elementλ₯Ό λ°˜ν™˜ν•œλ‹€.
<MyContext.Consumer>
  {value => /* context 값을 μ΄μš©ν•œ λ Œλ”λ§ */}
</MyContext.Consumer>

useContext

  • Context에 μžˆλŠ” 값을 μ‚¬μš©ν•  λ•Œ Consumer λŒ€μ‹  useContextλ₯Ό μ΄μš©ν•  수 μžˆλ‹€.
const value = useContext(MyContext);

static contextType

  • ν΄λž˜μŠ€ν˜• μ»΄ν¬λ„ŒνŠΈμ—μ„œ Contextλ₯Ό μ’€ 더 μ‰½κ²Œ μ‚¬μš©ν•˜κ³  μ‹Άλ‹€λ©΄ static contextType을 μ‚¬μš©ν•  수 μžˆλ‹€.
  • static contextType 값을 Context둜 μ§€μ •ν•˜λ©΄ this.contextλ₯Ό μ‘°νšŒν–ˆμ„ λ•Œ ν˜„μž¬ Context의 valueλ₯Ό κ°€λ¦¬ν‚€κ²Œ λœλ‹€.
class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}
  • static contextType을 μ •μ˜ν•˜λ©΄ 클래슀 λ©”μ„œλ“œμ—μ„œλ„ Context에 λ„£μ–΄ λ‘” ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  수 μžˆλ‹€.
  • ν•˜μ§€λ§Œ, ν•œ ν΄λž˜μŠ€μ—μ„œ ν•˜λ‚˜μ˜ Context만 μ‚¬μš©ν•  수 μžˆλ‹€.

0개의 λŒ“κΈ€