[ReactJS] 전역 상태 관리 도구 Context API

Tim·2022년 3월 31일
0

ReactJS

목록 보기
2/5
post-thumbnail

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;
profile
HTML5, CSS3, JavaScript, Typescript, React 프론트엔드 개발자입니다.

0개의 댓글