-
context APIJavascript/React.js 2020. 5. 13. 20:53
context API
프로젝트에서 전역적으로 사용할 데이터(로그인 정보, 앱 환경 설정 등)가 있을 때 유용한 기능이다.
리액트는 컴포넌트 간에 데이터를 props로 전달하기 때문에 컴포넌트 여기저기서 필요한 데이터는 최상위 컴포넌트인 App의 state에 넣어서 관리한다.
여기서 G 컴포넌트는 전역 상태를 업데이트하고, F와 J 컴포넌트는 리렌더링한다고 가정하자. 그리고 App이 지니고 있는 value를 F,G 컴포넌트에 전달하려면 여러 컴포넌트를 거쳐 불편하다.
이렇게 context API를 사용하면 context를 만들어 단 한 번에 원하는 값을 받아올 수 있다.
예제
src/contexts
-> color.js : context 데이터 관리
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React, { createContext, useState } from 'react'; // context 생성. 상태는 state, 업데이트 함수는 actions const ColorContext = createContext({ state: {color: 'black', subcolor: 'red'}, actions: { setColor: () => {}, setSubcolor: () => {} } }); // 컬러 변경사항을 자손들에게 제공 const ColorProvider = ({ children }) => { const [color, setColor] = useState('black'); const [subcolor, setSubcolor] = useState('red'); const value = { state: {color, subcolor}, actions: {setColor, setSubcolor} }; return ( <ColorContext.Provider value={value}>{children}</ColorContext.Provider> ); }; // value 변경 사항을 구독하며, 가장 가까운 Provider value 참조 // const ColorConsumer = ColorContext.Consumer; const {Consumer : ColorConsumer} = ColorContext; export {ColorProvider, ColorConsumer}; export default ColorContext; src/components
-> ColorBox.js : 색상 box를 보여주는 컴포넌트
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React from 'react'; import { ColorConsumer } from '../contexts/color'; const ColorBox = () => { return ( <ColorConsumer> {/* 컴포넌트 사이에 중괄호를 열어서 그 안에 함수를 넣는 패턴을 Function as a child라고 한다.*/} {/* 컴포넌트의 children이 있어야 할 자리에 함수를 전달하기 때문이다. */} {({ state }) => ( <> <div style={{width: '64px', height: '64px', background: state.color}}/> <div style={{width: '32px', height: '32px', background: state.subcolor}}/> </> )} </ColorConsumer> ); }; export default ColorBox; -> SelectColor.js : context 색상을 변경하는 컴포넌트
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React from 'react'; import { ColorConsumer } from '../contexts/color'; // 변경 가능한 색상 const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; const SelectColors = () => { return ( <div> <h2>choose color</h2> <ColorConsumer> {({ actions }) => ( <div style={{display: 'flex'}}> {colors.map(color => ( <div key={color} style={{ background: color, width: '24px', height: '24px', cursor: 'pointer'}} // 왼쪽 클릭 시, color 변경 onClick={() => actions.setColor(color)} // onContextMenu는 우클릭 이벤트, subcolor 변경 onContextMenu={e => { e.preventDefault(); actions.setSubcolor(color); }} /> ))} </div> )} </ColorConsumer> <hr/> </div> ); }; export default SelectColors; src/App.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React from 'react'; import ColorBox from './components/ColorBox'; import { ColorProvider } from './contexts/color'; import SelectColors from './components/SelectColors'; // Provider를 사용하면 context 값을 변경할 수 있다. const App = () => { return ( <ColorProvider> <div> <SelectColors/> <ColorBox/> </div> </ColorProvider> ); }; export default App; useContext
Hook 중에서 useContext를 사용하면 아주 편하게 사용할 수 있다. ColorBox.js 컴포넌트의 코드를 다음과 같이 간결하게 할 수 있다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersimport React, { useContext } from 'react'; import ColorContext from '../contexts/color'; const ColorBox = () => { // useContext를 사용하면 간단하게 context를 사용할 수 있다. const { state } = useContext(ColorContext); return ( <> <div style={{width: '64px', height: '64px', background: state.color}}/> <div style={{width: '32px', height: '32px', background: state.subcolor}}/> </> ); }; export default ColorBox; 'Javascript > React.js' 카테고리의 다른 글
외부 API를 연동해 뉴스 뷰어 만들기 (0) 2020.05.12 SPA (0) 2020.05.11 immer (0) 2020.05.06 최적화 방법 (0) 2020.05.06 chrome 개발자 도구를 통한 성능 모니터링 (0) 2020.05.06