[ReactJS] 전역 상태 관리 도구 Context API
Context API
state를 전역으로 관리해서 props로 내려주지 않아도 어떤 컴포넌트에서든 사용하고 관리가 가능하도록 하는 전역 상태 관리 도구.
Context 설정하기
context.js
import React, { useReducer } from "react";
// Context 객체 선언
export const Context = React.createContext();
// useReducer 초기 상태 값 설정
const initialUser = [
{
id: 1,
name: 'apple'
},
{
id: 2,
name: 'banana'
},
{
id: 3,
name: 'cherry'
}
]
// useReducer action 처리 함수
function userReducer(oldUser, action) {
switch(action.type) {
case "INPUTUSER":
return [...oldUser, {id: action.id, name: action.name}];
case "REMOVEUSER":
return oldUser.filter((item) => item.id !== action.id);
default:
return oldUser;
}
}
// Provider 설정
const ContextProvider = ({ children }) => {
// useReducer를 사용해서 state와 dispatch를 생성
const [user, userDispatch] = useReducer(userReducer, initialUser);
return (
// Provider 컴포넌트는 value prop을 받아서 이 값을 하위에 있는 컴포넌트에게 전달
<Context.Provider value={{ user, userDispatch }}>
{children}
</Context.Provider>
);
}
export default ContextProvider;
App.js
import './App.css';
import Main from './pages/main';
import ContextProvider from './context';
/*
Provider 파일로 최상위 컴포넌트인 App.js 내부를 감싸주어
하위 컴포넌트 어느 곳에서도 Context를 이용해 value를
가져올 수 있도록 만들어줍니다.
*/
function App() {
return (
<ContextProvider>
<Main />
</ContextProvider>
);
}
export default App;
test.js
import React, { useCallback, useContext, useState } from 'react';
// context를 사용하려는 컴포넌트에 import
import { Context } from './context';
const Test = () => {
// useContext 함수에 파라미터로 Context 객체를 넘겨주고 value를 받아와 사용
const { user, userDispatch } = useContext(Context);
const [name, setName] = useState("");
const onClickhandler = useCallback(() => {
userDispatch({ type: "INPUTUSER", id: user[user.length - 1].id + 1, name: name });
setName("");
}, [userDispatch, user, name]);
return(
<div>
<input type="text" value={name} onChange={onChangehandler} />
<button onClick={onClickhandler}>입력</button>
</div>
);
}
export default Test;
Author And Source
이 문제에 관하여([ReactJS] 전역 상태 관리 도구 Context API), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@timcodejs/ReactJS-전역-상태-관리-도구-Context-API저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)