useContext

박서현·2023년 8월 29일
post-thumbnail
  • context
    : 전역적으로 사용하는 어떠한 것을 표현할 때 context라는 말을 쓴다.

  • prop drilling의 문제점
    • 깊이가 너무 깊어지면 이 prop이 어떤 컴포넌트로부터 왔는지 파악이 어려워진다.
    • 어떤 컴포넌트에서 오류가 발생 할 경우 추적이 힘들어진다.



usecontext를 사용하지 않을 경우


📁 component / GrandFather.jsx

import React from 'react'
import Father from './Father'

//GF -> Child한테 어떤 정보를 알려줘서 Child가 그 내용을 출력하도록
function GrandFather() {
  const houseName = '스파르타'
  const poketMoney = 10000
  return <Father
    houseName={houseName}
    poketMoney={poketMoney}
  />
}

export default GrandFather

📁 component / Father.jsx

import React from 'react'
import Child from './Child'

function Father({houseName, poketMoney}) {
  
  return <Child
    houseName={houseName}
    poketMoney={poketMoney}
  />
}

export default Father

📁 component / Child.jsx

import React from 'react'

const style = {
  color: 'red',
  fontWeight: '900'
}
function Child({houseName, poketMoney}) {
  console.log(houseName, poketMoney)
  return (
    <div>
      나는 이 집안의 막내 <br />
      할아버지가 우리 집 이름은 <span style={style}>{houseName}</span>이라고 하셨어요<br />
      게다가 용돈도 <span style={style}>{poketMoney}</span>만큼이나 주셨어요
    </div>
  )
}

export default Child




usecontext를 사용 할 경우


📁 context / FamilyContext.jsx

import { createContext } from "react";

export const FamilyContext =  createContext(null)

📁 component / GrandFather.jsx

import React from 'react'
import { FamilyContext } from '../context/FamilyContext'
import Father from './Father'

//GF -> Child한테 어떤 정보를 알려줘서 Child가 그 내용을 출력하도록
function GrandFather() {
  const houseName = '스파르타'
  const poketMoney = 10000
  return (
    <FamilyContext.Provider value={{
      houseName,
      poketMoney
    }}>
      <Father/>
    </FamilyContext.Provider>
  )

}

export default GrandFather

📁 component / Father.jsx

import React from 'react'
import Child from './Child'

function Father() {
  
  return <Child/>
}

export default Father

📁 component / GrandFather.jsx

import React, { useContext } from 'react'
import { FamilyContext } from '../context/FamilyContext'

const style = {
  color: 'red',
  fontWeight: '900'
}
function Child() {
  const data = useContext(FamilyContext)
  console.log('data', data)
  return (
    <div>
      나는 이 집안의 막내 <br />
      할아버지가 우리 집 이름은 <span style={style}>{data.houseName}</span>이라고 하셨어요<br />
      게다가 용돈도 <span style={style}>{data.poketMoney}</span>만큼이나 주셨어요
    </div>
  )
}

export default Child

GrandFather에서 Child에게 props로 값을 내려 준게 아니다!!

0개의 댓글