-
ContextAPI 사용하기React 2022. 11. 14. 08:52
리액트의 코어 라이브러리로 ContextAPI는 redux, recoil, mobX와 같은 라이브러리와는 다르게 설치 없이 사용할 수 있다.
최상위 컴포넌트부터 최하위 컴포넌트까지 모두 동일한 상태를 만들고 사용하기 위해서 ContextAPI와 같은 전역 상태 관리 도구를 이용할 수 있다.
// store.js import React, { useState } from "react"; export const MyContext = React.createContext(); const StateStore = (props) => { const [color, setColor] = useState("black"); const [direction, setDirection] = useState("row"); return ( <MyContext.Provider value={{ color, setColor, direction, setDirection }}> {props.children} </MyContext.Provider> ); } export default StateStore;- 위와 같이 createContext로 컨텍스트 객체를 만든다.
- value에 해당하는 값에 변화가 생기면, 리랜더링이 일어난다.
- createContext에 인자로 defaultValue를 넣으면, 값이 없을 때 이 defaultValue를 가진다.
// MyContext.js export const MyContext = React.createContext({ color: "red", setColor: () => {}, direction: "row", setDirection: () => {}, });- 위와 같이 createContext에 인자로 객체를 줘 상태의 초기값을 설정할 수 있다.
- 위의 코드는 적절한 Provider를 찾지 못했을 때 인자로 받은 기본값을 사용하게 된다.
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import StateStore from "./context/store"; ReactDOM.render( <React.StrictMode> <StateStore> <App /> </StateStore> </React.StrictMode>, document.getElementById('root') );- 만들어진 스토어를 컴포넌트 상단에 감싸 위치시킨다.
// Test.js import { useContext } from "react"; import { MyContext } from "../context/store"; const Test = () => { const context = useContext(MyContext); const handleColor = (e) => { context.setColor(e.target.value); } return ( <div> {context.color} <input type="text" placeholder="color?" onChange={(e) => handleColor(e)}/> </div> ); } export default Test;- useContext 훅을 사용하여 컨텍스트 객체를 선택하고 전역 상태를 사용할 수 있다.
- contextAPI는 createContext를 통해서 여러 개의 컨택스트 객체를 만들 수 있다.
- redux는 하나의 스토어만 사용이 가능한 것과 반대로 contextAPI는 여러 개의 스토어 객체를 사용할 수 있다.
- createContext의 인자로 초기값을 전달할 수 있는데, 적절한 Provider를 찾지 못했을 때 이 값이 쓰인다.
참고 자료 출처 (공식문서) : https://ko.reactjs.org/docs/context.html
Context – React
A JavaScript library for building user interfaces
ko.reactjs.org
https://beta.reactjs.org/reference/react/useContext
useContext
A JavaScript library for building user interfaces
beta.reactjs.org
https://beta.reactjs.org/reference/react/createContext
createContext
A JavaScript library for building user interfaces
beta.reactjs.org
'React' 카테고리의 다른 글
간단한 React 커스텀 훅(Custom Hook) 사용법 (1) 2022.11.18 간단하게 react-hook-form과 yup 사용하기 (0) 2022.11.18 axios의 interceptors 기능 사용하기 (1) 2022.11.11 useEffect의 Clean-up 함수 (1) 2022.11.10 코드 깔끔하게 작성하기 (리액트, Styled-Components) (0) 2022.11.10