[TIL] useContext

열심히하시는개발자·2021년 3월 5일
0
post-thumbnail

1. Context란?

  • 일반적인 React 애플리케이션에서 데이터는 부모로부터 자식에게 props를 통해 전달되지만, 애플리케이션 안의 여러 컴포넌트들에 전해줘야 하는 props의 경우 이 과정이 번거로울 수 있다. 그래서 context를 이용하면, 트리 단계마다 명시적으로 props를 넘겨주지 않아도 많은 컴포넌트가 이러한 값을 공유하도록 할 수 있다.

1.1 언제 context를 써야 할까?

  • context는 React 컴포넌트 트리 안에서 전역적이라고 볼 수 있는 데이터를 공유할 수 있도록 고안된 방법이다. 그러한 데이터로는 현재 로그인한 유저, 테마, 선호하는 언어 등이 있다.

1.2 useContext 업이 자식 구성요소에 데이터 전달

  • 특정 직원의 세부 정보를 포함하는 상위 구성 요소
import  React ,  {  useState }  from  "react" ;

function  UserDetailsComponent( )  {
  const  [ userDetails ,  setUserDetails ]  =  useState ( {
    name : "Bj" ,
    age : 27
  }) ;
  
return (
  <div>
    <h1> 상위 구성 요소 </h1>
    <ChildComponent userDetails={userDetails}></ChildComponent>
  </div>
  )
}

function  ChildComponent ( props )  {
  return  (
    <div>
      <h2> 하위 구성 요소 </h2>
      <SubChildComponent userDetails={props.userDetails}</SubChildComponent>
    </div>
  )
}

function  SubChildComponent ( props )  {
  return  (
    <div>
      <h3> 하위 구성 요소 </h3>
      <h4> Name : {props.userDetails.name} </h4>
      <h4> Age : {props.userDetails.age} </h4>
    </div>
  )
}
  • 부모 Component는 Component 내에서 사용되지 않는 일부 상태 변수를 정의하는 대신 자식 Component ChildComponent에 props를 전달한다.
  • 자식 Component인 ChildComponent 는 userDetails를 사용하지 않고 데이터를 하위 Component인 SubChildComponent에 props로 전달 된 데이터를 사용하고 구성 요소에 사용자 이름과 나이를 표시한다.

1.3 코드의 문제점!

  • props를 사용하지 않는 하위 Component 요소에도 props를 명시 적으로 계속 전달해야한다.
    그렇기 때문에 전체 구조에 거쳐 props 데이터를 지속적으로 전달하는 오버헤드가 발생한다.

2. Context API란?

  • 하위 Component에서 props 데이터가 필요하기 때문에 필요하지 않는 Component에도 props 데이터를 전달하는 문제들을 해결하기 위해 Context API를 사용할 수 있다.

2.1 Context API 예시

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

const userDetailContext = React.createContext(null);

export default function  UserDetailsComponent ( )  {
  let  [userDetails]  =  useState ({
    name : "Bj" ,
    age : 27
  }) ;

  return  (
    <userDetailContext.Provider  value = {userDetails}>
      <h1> 상위 구성 요소 </h1>
      <ChildComponent  userDetails={userDetails}/>
    </userDetailContext.Provider>
  ) ;
}

✅React.createContext(null)

  • Context를 사용할 때는 다음과 같이 React.createContext() 라는 함수를 사용한다.
  • createContext의 파라미터에는 Context의 기본값을 설정할 수 있고, 여기서 설정하는 Context를 쓸 때 값을 따로 지정하지 않을 경우 사용되는 기본 값이다.

✅Provider 와 value

  • Context를 만들면, Context안에 Provider라는 Component가 들어있는데 이 Component를 통하여 Context의 값을 정할 수 있고, 이 Component를 사용할 때 value라는 값을 설정해주면 된다.
import React, { useState ,createContext} from "react";

const userDetailContext = React.createContext(null);

export default function UserDetailsComponent() {
  let [userDetails] = useState({
    name: "Bj",
    age: 27
  });

  return (
    <userDetailContext.Provider value={userDetails}>
      <h1>상위 구성 요소</h1>
      <ChildComponent userDetails={userDetails} />
    </userDetailContext.Provider>
  );
}

function ChildComponent() {
  return (
    <div>
      <h2>하위 구성 요소</h2>
      <SubChildComponent />
    </div>
  );
}

function SubChildComponent(props) {
  const contextData = React.useContext(userDetailContext);
  return (
    <div>
      <h3>하위 구성 요소</h3>
      <h4>User Name: {contextData.name}</h4>
      <h4>User Age: {contextData.age}</h4>
    </div>
  );
}
  • useContext를 사용하여 props를 전달하지 않고 SubChildComponent에서 props를 사용할 수 있다.

3. 결과

0개의 댓글