1. ContextAPI ?

ContextAPI는 리액트의 내장 기능으로, 컴포넌트 끼리 값을 쉽게 공유할 수 있게 해주며, Props Driling을 방지합니다. 주로 전역 상태를 관리할때 사용됩니다.

ContextAPI 사용방법

1 ) context 생성하기

Context를 사용하기 위해서는 Context를 생성해야합니다. Context는 createContext를 이용하여 생성할 수 있습니다. createContext 안에는 초기값을 넣어주면 됩니다.

import { createContext } from "react";

exprot const userContext = createContext({ user:"test" });

2 ) Context.Consummer로 컴포넌트 감싸기

Consumner은 Context를 구독하는 컴포넌트입니다. Consumer를 값을 전달해줄 컴포넌트에 감싸줍니다. Consumer은 콜백함수 형태로 context에서 정의한 값을 가져올 수 있습니다.

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

export const userContext = createContext({user:"test"});

function App() {
  const [user, setUser] = useState("");
  const [id, setId] = useState("");
  const [password, setPassword] = useState("");

  const onClickSubmit = (e) => {
    e.preventDefault();
    if (id === "test" && password === "1234") {
      setUser("test");
    }
  };
  return (
    <UserContext.Consumer>
    {(value)=>(
    <>
        <form onSubmit={onClickSubmit}>
    	<p>현재 아이디 : {value.user}</p>
        <input
          type="text"
          value={id}
          placeholder="아이디"
          onChange={(e) => setId(e.target.value)}
        />
        <input
          type="password"
          value={password}
          placeholder="비밀번호"
          onChange={(e) => setPassword(e.target.value)}
        />
        <button type="submit">로그인</button>
      </form>
</>
  	)}

    </UserContext.Consumer>
  );
}

export default App;

3 ) context.provider로 자식 컴포넌트 감싸기

자식 컴포넌트에 값을 전달하기 위해서는 Provider를 사용해야합니다. Provider는 컴포넌트 계층 구조에서 Context 객체를 전달하는 역할을 합니다. Provider를 이용하여 Context를 사용할 컴포넌트를 감싸준 후 value에 전역으로 관리할 값들을 넣어줍니다.

import { useState, createContext } from "react";
import Main from "./Main";
export const UserContext = createContext({ user: "test" });

function App() {
  const [user, setUser] = useState("");
  const [id, setId] = useState("");
  const [password, setPassword] = useState("");

  const onClickSubmit = (e) => {
    e.preventDefault();
    if (id === "test" && password === "1234") {
      setUser("test");
    }
  };
  return (
    <>
      {user ? (
        <UserContext.Provider value={{ user }}>
          <Main />
        </UserContext.Provider>
      ) : (
        <UserContext.Consumer>
          {(userInfo) => (
            <div>
              <p>초기 아이디 : {userInfo.user}</p>
              <form onSubmit={onClickSubmit}>
                <input
                  type="text"
                  value={id}
                  placeholder="아이디"
                  onChange={(e) => setId(e.target.value)}
                />
                <input
                  type="password"
                  value={password}
                  placeholder="비밀번호"
                  onChange={(e) => setPassword(e.target.value)}
                />
                <button type="submit">로그인</button>
              </form>
            </div>
          )}
        </UserContext.Consumer>
      )}
    </>
  );
}

export default App;

Main 컴포넌트

import React, { useContext } from 'react'
import UserContext from './context/usercontext';

export default function Main() {
  const {user} = useContext(UserContext);
  return (
    <div>{user}님 환영합니다!</div>
  )
}