프론트 앤드(Front-End)/React

[React Hook] Context API 사용법 useContext

RyanSin 2021. 1. 22. 12:55
반응형

- 지난 시간

안녕하세요. 지난 시간에는 useEffect를 사용하는 방법에 대해서 알아봤습니다.

 

혹시 놓치고 오신 분들은 아래 링크를 통해 확인하고 와주세요. :)

any-ting.tistory.com/23

 

[React Hook] useEffect 사용 (Function Life Cycle)

- 지난 시간 안녕하세요. 지난 시간에는 Function Component를 만들고 useState를 사용하는 방법에 대해서 알아봤습니다. 혹시 놓치고 오신 분들은 아래 링크를 통해 확인하고 와주세요. :) any-ting.tistory.c

any-ting.tistory.com

- 개요

이번 시간에는 Context API를 사용하는 법에 대해 알아보겠습니다.

 

일단 Context API란 무엇일까요? 공식 홈페이지에서는 아래와 같이 설명하고 있습니다.

 

공식 홈페이지 자료

Component들이 서로  props로 값을 하나하나 전달하지 않아도 데이터를 공유할 수 있다는 말입니다.

 

만약 Context API가 없다면 props로 일일이 데이터를 넘겨줘야 합니다. Component에 깊이가 깊지 않다면 괜찮겠지만...

 

깊이가 정말... 깊다면... 정말 정말 깊다면... 불편하겠죠?

 

(정말 큰 프로젝트는... 엄청 깊어요 ㅠㅠ....)

 

props 사용

위와 같은 Component 구조가 있다고 생각해보겠습니다.

 

만약에 C라는 Component에서 있는 값을 E라는 Component에게 값을 전달하고 싶다면 C => B=> A => D=> E 순으로 데이터를 전달해야 합니다... 정말... 번거롭겠죠?...

 

이럴 때 하나에 공용 저장 공간을 만들어서 데이터를 공유하면 편하겠죠??

 

Context API 사용

 위와 같이 Context API를 사용하면 props를 사용하지 않고 자원을 공유할 수 있어서 편리합니다 :)

 

- 사용법

import React, { createContext, useState } from 'react'; // createContext를 불러온다.

//하나의 Context를 생성합니다.
export const UserInfoContextStore = createContext();

/**
 * Context를 생성할 때 기본 값을 세팅한다. 
 * React에서는 값을 컨트롤 할 때는 Component를 만들어 사용하는걸 지향한다.
 *
 * **/
const UserInfoContext = (props) => {

    const [ name, setName ] = useState(); // 유저 이름
    const [ age, setAge] = useState(); // 유저 나이
    
    //유저 정보를 하나의 객체로 만들어준다.
    const UserInfo = {
        name,
        setName,
        age, 
        setAge
    }

    /**
     * UserInfoContextStore.Provider : Provider는 구독(하위 Component)하고 있는 자식 Component에게 정보를 보내준다는 설정
     * value={UserInfo} : 자식 Component에게 값을 전달하기 위한 설정
     * {props.children} : 자식 Component를 랜더링 하기위해 설정
     */
    return (<UserInfoContextStore.Provider value={UserInfo}>{props.children}</UserInfoContextStore.Provider>);
};

export default UserInfoContext;

위 코드는 하나의 Context API 저장소입니다.

 

export default UserInfoContext는 다른 Component들을 감싸기 위해 필요하며, export const UserInfoContextStoro는 실제 설정한 데이터를 접근하기 위해서 사용되는 코드입니다.

 

주석을 하나하나 읽어보시면 이해가 가실 겁니다.

 

저장소를 만들었으니 이제 다른 컴포넌트에게 알려줘야 됩니다. 

 

그리고 설정한 기본 값을 가져다 사용해야겠죠? 여기서 사용되는 Hook이 있습니다. useContext Hook입니다.

 

그럼 세팅을 해보겠습니다.

 

1. UserInfoContext 설정

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import UserInfoContext from './Stores/UserInfoContext';

ReactDOM.render(
  <React.StrictMode>
  
    {/* UserInfoContext가 App Component를 감싸준다. */}
    <UserInfoContext>
      <App />
    </UserInfoContext>
    
  </React.StrictMode>,
  document.getElementById('root')
);

하위 자식 Component에게 정보를 보내주기 위해  App Component를 감싸줍니다. 그러면 App Component 하위 Component에게도 값을 전달합니다.

 

이렇게 설정하면 App 자식 컴포넌트들은 저장소에 접근해서 데이터를 받아올 수 있습니다.

 

간단한 예시를 보여드리겠습니다. 구조는 App => UserContainer => User 이런 식으로 Component로 만들어져 있습니다.

 

2. UserInfoContextStore 등록

import React, { useContext } from 'react'; // useContext를 불러온다.

//UserInfoContext 안에 Context를 가져온다.(UserInfoContextStore)
import { UserInfoContextStore } from '../Stores/UserInfoContext';

const style = {
    container: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      marginTop: "150px"
    },
}

const User = () => {

  //useContext를 사용해서 Store를 등록해줍니다.
  const UserInfo = useContext(UserInfoContextStore)

  //등록이 끝나면 이제 UserInfo 변수에는 우리가 설정한 유저정보가 있습니다.

    return (
        <div style={style.container}>
            이름 : {UserInfo.name}
        </div>
    );
};

export default User;

위 코드를 보면 첫 번째로 useContext와 UserInfoContext를 불러옵니다.

 

그리고 서로를 연결합니다. (const UserInfo = useContext(UserInfoContextStore))

 

이렇게 연결을 하면 끝입니다!! :)

 

이제 UserInfo 변수에서 원하는 값을 가져다가 사용하면 됩니다.

 

결과 화면

이번 시간에는 Context API에 대해서 알아봤습니다. :)