Context API

미숙한 초보 코딩.Js·2019년 10월 26일
0

Technical

목록 보기
2/6

다른 컴포넌트나 파일에서 값을 전달하지않고 바로 불러와서 사용할 수 있다.


Context API 를 사용하지 않고 전달

import React from "react";

function Child({ text }) {
  return <div>안녕하세요 {text}</div>;
}

function Parent({ text }) {
  return <Child text={text} />;
}

function GrandParent({ text }) {
  return <Parent text={text} />;
}

function Context() {
  return <GrandParent text="Good" />;
}

export default Context;

Context API를 이용한 전달

import React, { createContext, useContext } from "react";

const MyContext = createContext("default");

function Child() {
  const text = useContext(MyContext);
  return <div>안녕하세요 {text}</div>;
}

function Parent({ text }) {
  return <Child text={text} />;
}

function GrandParent({ text }) {
  return <Parent text={text} />;
}

function Context() {
  return (
    <MyContext.Provider value="Good">
      <GrandParent />
    </MyContext.Provider>
  );
}

export default Context;

createContext 를 이용하여 'default' 값을 설정한 다음 MyContext.Provider로 전달하고 싶은 컴퍼넌트에서 감싼뒤 value의 값으로 전달 하게됩니다. 그렇게 되면 default 는 value의 값인 'Good'이 들어오면서 바뀌게 됩니다.
그렇게 되면 useContext를 사용하면 됩니다.

profile
힘들땐 블로그 하나더 적자!!![ Suyang ]

0개의 댓글