React Hook + Context API

React Hook + Context API

기존에 사용하던 원리와 동일합니다. Provider 내부에 있는 children은 Context의 영향을 받아 props를 자유롭게 받을 수 있습니다.

🚗 생성

src 폴더에 context.js를 생성한 후 다음과 같이 입력합니다. context.js는 일종의 DB warehouse가 될 것입니다. 여기서는 UserContext 하나만 만들지만 원하는 Context를 마음대로 만들 수 있습니다.

import React from "react"; // Context는 추후 사용할 컴포넌트에서 Context를 생성합니다 export const UserContext = React.createContext(); // Provider는 추후 최상위 컴포넌트를 감쌉니다. const UserContextProvider = ({ children }) => { return ( {children} ); }; export default UserContextProvider;

🚓 적용 및 사용

이제 최상위 컴포넌트를 Provider로 감싸줍니다. (여기서는 UserContextProvider 입니다) 이 방식을 이용하면 이제 이 컴포넌트의 아래에 존재하는 컴포넌트는 Context의 정보를 자유롭게 사용할 수 있게 됩니다. 물론 여기서는 기껏해봐야 value라는 props 하나 뿐입니다.

const App = () => { return ( ); };

context를 사용할 곳에서 context를 불러오면 됩니다. React 객체 내부의 useContext 메소드를 활용하여 가져올 수 있습니다. React.userContext(정의한 Context). 여기서는 UserContext입니다. (위 context.js를 살펴보면 알 수 있습니다)

import React from "react"; import { UserContext } from "./context"; const Header = () => { const context = React.useContext(UserContext); console.log(context); // 앞서 정의한 props가 전달됩니다. return ( Home Hello, {context.name} ); }; export default Header;

🚕 state와 함께 Context 사용하기

다음과 같이 state를 작성하고 그것을 props로 넘김으로써 state도 사용할 수 있습니다. 이 방법은 함수도 다른 컴포넌트로 넘길 수 있어 유용하고, context에서도 대개는 이런 방식으로 사용합니다.

import React, { useState } from "react"; export const UserContext = React.createContext(); const UserContextProvider = ({ children }) => { const [user, setUser] = useState({ name: "darren", loggedIn: false }); const logUserIn = () => setUser({ ...user, loggedIn: true }); return ( {children} ); }; export default UserContextProvider;

from http://darrengwon.tistory.com/182 by ccl(A) rewrite - 2020-03-24 04:20:15

댓글

이 블로그의 인기 게시물

단위 테스트 환경 구축

Coupang CS Systems 채용 정보: Front-end 개발자를 찾습니다!

스토리북에서 스토리를 작성하는 방법