본문 바로가기
front-end/React

[React]Hook: useContext

by -제이리 2022. 8. 23.
728x90
320x100

 

useContext 란?

context는 부모가 자식컴포넌트에게 일일이 props를 넘겨주지 않고도 컴포넌트 트리 전체에 데이터를 전달할 수 있게 해준다. 

useContext는 context를 좀더 편하게 사용할 수 있도록 도와주는 hook이다.

 

 

Context API 3가지 주요 개념

- createContext(initialValue)

- Context.Provider

- useContext(Context)


createContext(initialValue) -> 부모컴포넌트에 작성

  • context객체를 생성한다.
  • Provider와 Consumer 를 반환한다.
    • Provider : 생성한 context를 하위 컴포넌트에게 전달하는 역할을 한다.
    • Consumer : context의 변화를 감시하는 컴포넌트이다.
  • 파라미터 initialValue는 Provider를 사용하지 않았을 때 적용될 초기값을 의미한다.

 

Context.Provider -> 부모컴포넌트에 작성

  • 생성한 context를 하위 컴포넌트에 전달하는 역할을 한다.

App.js

// App.js

import React, { useState, createContext } from "react";
import Mart from "./components/Mart";

export const AppContext = createContext(); // context생성

const initialValue = {
   name: 'kim',
   age: 20
};

  return (
    <>
      <AppContext.Provider value={initialValue}> // Provider로 하위컴포넌트를 감싼다.
        <Children />
      </AppContext.Provider>
    </>
  );
}
export default App;

 


 

useContext(Context) -> 자식컴포넌트에 작성

  • context의 변화를 감시하는 역할
  • 설정한 상태를 불러올 때 사용
  • Context.Consumer를 사용할 수 있지만 hook을 사용하는것이 좀더 깔끔하다.

 

Children.js (.Consumer사용)

//Children.js

// .Consumer 사용시
import React from "react";
import { AppContext } from "./App";

const Children = () => {
  return (
      <AppContext.Consumer> // .Consumer로 감싸준다.
        {(initialValue) => (
          <>
            <h3>이름은 {initialValue.name}입니다.</h3>
            <h3>나이는 {initialValue.age}입니다.</h3>
          </>
        )}
      </AppContext.Consumer>
  );
};

export default Children;

Children.js (useContext 사용)

//Children.js

// useContext hook사용시
import React, { useContext } from "react";
import { AppContext } from "./App";

const Children = () => {
  const initialValue = useContext(AppContext); // useContext hook사용. 
  return (
          <>
            <h3>이름은 {initialValue.name}입니다.</h3>
            <h3>나이는 {initialValue.age}입니다.</h3>
          </>
  );
};

export default Children;
728x90
320x100

'front-end > React' 카테고리의 다른 글

[Redux]리덕스의 기본개념  (0) 2022.08.24
[React]Hook: customHook  (0) 2022.08.24
[React] Hook: useReducer  (0) 2022.08.16
[React]Hook: useMemo()와 useCallback() / React.memo()  (0) 2022.08.16
[React]Hook: useEffect()  (0) 2022.08.15

댓글