카테고리 없음

react) context api

EverJunior Minjoo 2023. 11. 1. 14:51

보통 props 를 통해서 데이터를 부모컴포넌트와 자식컴포넌트 사이에 전달하는데,

만약 구조가 a - b - c 에서 a 의 데이터가 c에서 필요하다면 이때 불필요하게 a에서 b로 넘겨서 다시 c 로 넘겨야한다. 그럼 불필요한 코드작성을 해야하게 되는데 이때 컨텍스트는 데이터의 공급자와 소비자를 정의하고, 데이터가 필요한 컴포넌트만 사용할수 있게 구현하도록 한다.

사용은 리액트의 기본제공 함수인 createContext를 호출하고, 공급자, Provider와 소비자 Consumer를 받아 사용할수 있도록한다.

그리고 하위 컴포넌트에서 소비자를 사용할수 있도록 export 해준다.

const {Provider, Consumer} = react.createContext()
export {Consumer}

자식 컴포넌트를 Provider 태그로 감싸고 전달할 데이터를 value값으로 할당한다.

 <Provider value={"react200 from parent"}>       
        <Children></Children>     
 </Provider>
import react, { Component } from 'react';
import Children from './contextChildren';
//
const {Provider, Consumer} = react.createContext()
export {Consumer}

class R076_ContextApi extends Component{
    render(){
        return(
            <Provider value={"react200 from parent"}>
                <Children></Children>
            </Provider>
        )
    }
}

export default R076_ContextApi

중간 자식 컴포넌트에서는 에서는 부모 컴포넌트의 데이터를 사용하지 않고, 손자 컴포넌트의 contextChildren2를 리턴한다. 손자 컴포넌트에서 사용할 데이터를 전달하지않아도 된다.

import react from 'react'
import Children2 from './contextChildren2';

class contextChildren extends react.Component{
    render(){
        return(
            <Children2></Children2>
        )
    }
}
export default contextChildren;
import react from 'react'
import { Consumer } from './R076_ContextApi'

class contextChildren2 extends react.Component{
    render(){
        return(
            <Consumer>
                {contextvalue=> <h3>{`contextValue 222 : ${contextvalue}`}</h3>}
            </Consumer>
        )
    }
}
export default contextChildren2

그럼 이제 c 컴포넌트에서 a 부모컴포넌트의 데이터를 사용하기위해서 a컴포넌트에서 익스포트한 Consumer를 임포트해서 사용할수 있게 한다. 

Consumer태그로 출력할 요소를 감싸서, a 부모컴포넌트에서 value에 할당했던 데이터를 contextValue변수로 받아 출력한다.

 

** 컨텍스트를 사용하면, 하위 컴포넌트가 여러개인 구조에서 유용하게 사용할수있다. 몇번째 하위 컴포넌트인지 상관없이 그냥 필요한 하위 컴포넌트에서 Consumer를 import 해서 필요한 데이터를 사용한다.


props는 데이터가 부모에서 자식 컴포넌트로 단방향으로만 이동할수 있는데 컨텍스트를 사용하면 자식 컴포넌트에서 부모 컴포넌트의 데이터를 변경할수있다.

(이부분도 생활코딩에 설명에 녹아있던 부분인것같다)