우리가 값들의 상태관리를 하기 위해서는 useState를 사용할수있다. 그렇지만 전역으로 상태관리를 하기위해서는 레벨업이 필요하다! 그렇다면 전역으로 상태관리를 하기위한 다음 스텝! Context API에 대해서 공부해보자!
= context api를 사용하면 전역으로 상태를 관리 할 수 있게 된다.
보통 우리가 리액트를 사용하면서 데이터를 넘겨주고 싶을때 우리는 props를 사용해서 부모에서 자식에게로 데이터를 전달해줄수 있다. 이때, 트리의 깊이가 깊지 않다면 데이터를 props로 전달 전달 해주면서 사용을 할 수 있지만, 트리의 깊이가 깊어지게 되면 트리 위쪽에 값을 저장하고 그걸 props의 props의 props의 data와 같이 전달 해주게 된다. 그러면 내가 사용하고 싶은 데이터와 상관없는 컴포넌트에서 데이터를 받아줘야 하며, 전달 전달 하는 과정이 매우 번거롭게 느끼게 되고 코드도 어지러워진다.
그럴때 우리는 context api를 꺼내들면 된다!
Username.js컴포넌트에서 이름을 받아오고, Color.js컴포넌트에서 좋아하는 컬러를 받아올것이다. 받아온 데이터를 Show.js에서 화면에 보여주고 싶다고 해보자.
가장 먼저 해야할일. context api를 생성하자. user.js라는 파일에 생성을 할 것이다. 아래와 같이 생성 할수있다.
user.js
// 리액트와 함께 createContext를 import 해주기
import React, { createContext } from "react";
// UserContext라는 이름으로 context api를 생성
export const UserContext = createContext();
// UserStore라는 이름으로 어떤 데이터를 만들지 생성
const UserStore = (props) => {
const users = {
username : "",
favoriteColor : ""
}
return (
// Provider를 사용해서 감싸주기
<UserContext.Provider value={users}>
{props.children}
</UserContext.Provider>
);
};
export default UserStore;
생성이 끝났다면 어디서 이 데이터를 사용하고 싶은지 지정해주자. App.js에서 어느 컴포넌트들에서 데이터를 사용하고 싶은지 지정.
App.js
// UserStore를 user.js에서 받아오기
import React from 'react'
import UserStore from "user";
function App(){
return(
<>
// 받아온 UserStore를 어느 컴포넌트에서 사용할건지 지정
// 사용하고 싶은 컴포넌트를 감싸는 형태로 만들어주기
<UserStore>
<Username />
<Color />
<Show />
<UserStore/>
</>
)
}
그렇다면 context api를 useContext를 사용해서 적용해보자.
Username.js
import React, { useContext, useState, useEffect } from 'react';
import { UserContext } from "../store/user";
export function Username(){
const [username, setUsername] = useState("");
const context = useContext(UserContext);
useEffect(()=>{
context['username'] = username;
}, [ username ])
return <input
type="text"
value={usernmae}
onChange={(e)=>{setUsername(e.target.value)}} />
}
Color.js
import React, { useContext, useState, useEffect } from 'react';
import { UserContext } from "../store/user";
export function Color(){
const [color, setColor] = useState("");
const context = useContext(UserContext);
useEffect(()=>{
context['color'] = color;
}, [ color ])
return <input
type="text"
value={color}
onChange={(e)=>{setColor(e.target.value)}} />
}
Show.js
import React, { useContext, useState, useEffect } from 'react';
import { UserContext } from "../store/user";
export function Show(){
const context = useContext(UserContext);
return(<>
<div>{context.username}</div>
<div>{context.color}</div>
</>)
}
이렇게 해주면 화면에 결과는 어떻게 나올까?
input값으로 받은 username
input값으로 받은 color
다른 컴포넌트에서도 값을 사용할 수 있게 되고, 전역적으로 상태관리가 가능하게 된다!
이렇게 비교적 Context api 는 사용법이 간단하다. 생성하는법만 간단히 익히게 되면 전역적으로 객체를 사용하는것 처럼 전역 상태관리가 가능하게 된다. 그렇다면 전역적으로 값의 상태 관리를 하기 위한 다음 스텝은
reduce,redux가 있다. 다음번에는reduce,redux에 대해서 공부해보고 싶다.