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๊ฐ์ ์ฐจ์ด์ ์ ๋ํ ์ํฐํด์ด ์์ผ๋ ์ฐธ๊ณ ๋ฐ๋๋๋ค. (์์ง ๋ฆฌ๋์ค๋ฅผ ๋ฐฐ์ฐ์ง ์์์ ์ฐจ์ด๋ ๋ฆฌ๋์ค ๊ฐ์ ๋ง์๋๋ฆฌ๋๋ก ํ๊ฒ ์ต๋๋ค.)
ย