본문 바로가기
Study/Udemy-React-완벽 가이드

10.3 Reducer 사용하여 부작용 처리 & Context API 사용하기 : Context API (feat. 유데미 React 완벽 가이드)

by NFAP0221S 2022. 6. 1.

https://www.udemy.com/course/best-react/

 

【한글자막】 React 완벽 가이드 with Redux, Next.js, TypeScript

Javascript부터 웹 어플리케이션 배포까지, React와 프론트엔드 최신 기술을 가장 쉽고 확실하게 배우는 법

www.udemy.com

이 게시물은 유데미 React 완벽 가이드 강의를 보고 메모를 남기는 게시물 입니다.


Context API

context는 prop이 많은 컴포넌트를 거쳐 많은 데이터를 전달 해야하는 문제가 있는 경우에 사용한다.

즉, 전역적으로 사용할 데이터가 있을 때 유용한 기능이다.

 

store이라는 폴더를 만들어서 전역적으로 사용하는 데이터를 관리해주는 파일을 만들어준다.

store

App에서 관리되던 데이터를 auth-context.js 파일로 옮겨 한곳에거 관리되도록 한다.

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

const AuthContext = React.createContext({
  isLoggedIn: false,
  onLogout: () => {}, // 자동 완성을 위한 더미 함수
  onLogin: (email, password) => {}, // 자동 완성을 위한 더미 함수
});

export const AuthContextProvider = (props) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    const storedUserLoggedInInformation = localStorage.getItem("isLoggedIn");

    if (storedUserLoggedInInformation === "1") {
      setIsLoggedIn(true);
    }
  }, []);

  const logoutHandler = () => {
    localStorage.removeItem("isLoggedIn");
    setIsLoggedIn(false);
  };

  const loginHandler = () => {
    localStorage.setItem("isLoggedIn", "1");
    setIsLoggedIn(true);
  };

  return (
    <AuthContext.Provider
      value={{
        isLoggedIn: isLoggedIn,
        onLogout: logoutHandler,
        onLogin: loginHandler,
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};

export default AuthContext;

# auth-context.js

Context API 사용하기

React.createContext 함수로 사용한다.

const AuthContext = React.createContext({
  isLoggedIn: false,
  onLogout: () => {}, // 자동 완성을 위한 더미 함수
  onLogin: (email, password) => {}, // 자동 완성을 위한 더미 함수
});

provider를 사용하면 context의 value 값을 변경 할 수있다.

value 값은 state를 이용하여 context를 동적으로 사용할 수 있다.

  return (
    <AuthContext.Provider
      value={{
        isLoggedIn: isLoggedIn,
        onLogout: logoutHandler,
        onLogin: loginHandler,
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );