Context API에서 Context.consumer로 전달하던 방식을 Hooks의 useContext를 사용해서 더 편하게 값을 전달할 수도 있습니다.
기존에 있었던 코드를 주석처리 하였으니 비교해보세요.
useContext 적용하기
import { useContext, createContext } from "react"; const UserInfo = createContext({ name: "gary", id: "garyIsFree" }); const App = () => { return ( <HelloLicat/> ); }; // const HelloLicat = () => { // return ( // <UserInfo.Consumer> // {(value) => ( // <div> // <input type="text" /> // <h2>{value.name}</h2> // <strong>{`@ ${value.id}`}</strong> // </div> // )} // </UserInfo.Consumer> // ); // }; const HelloLicat = () => { const { name, id } = useContext(UserInfo); return ( <div> <h2>{name}</h2> <strong>{id}</strong> </div> ); }; export default App;
useContext 자손 컴포넌트에 적용하기
import { useContext, createContext } from "react"; const UserInfo = createContext({ name: "gary", id: "garyIsFree" }); const App = () => { return ( <HelloLicat/> ); }; // const HelloLicat = () => { // return ( // <UserInfo.Consumer> // {(value) => ( // <div> // <input type="text" /> // <h2>{value.name}</h2> // <strong>{`@ ${value.id}`}</strong> // </div> // )} // </UserInfo.Consumer> // ); // }; const HelloLicat = () => { const { name, id } = useContext(UserInfo); return ( <div> <h2>{name}</h2> <strong>{id}</strong> <HelloLicatTwo/> </div> ); }; const HelloLicatTwo = () => { const { name, id } = useContext(UserInfo); return ( <div> <h2>{name}</h2> <strong>{id}</strong> </div> ); }; export default App;
하지만 Hooks의 useContext는 함수형 컴포넌트에서만 사용할 수 있습니다.
Context는 props가 아닌 전역으로 전달하기 때문에 부모에서 자식으로(부모 → 자식) 흐름의 전달 없이도 편하게 값을 전달할 수 있습니다. 그래서 Context를 사용하는 이유는 프로젝트의 컴포넌트 구조가 복잡해지면서 props로 전달하는데 한계가 있기 때문입니다. 하지만 props로의 전달로 충분히 가능하다면 Context를 사용하여 전역으로 전달할 필요가 없습니다.
리덕스를 사용하는 이유와 Context를 사용하는 이유가 비슷한데요. 읽어볼만한 글에 2개의 차이점에 대한 아티클이 있으니 참고바랍니다. (아직 리덕스를 배우지 않아서 차이는 리덕스 가서 말씀드리도록 하겠습니다.)