React 공식 문서 정리 - 3.4

김석·2023년 10월 5일
0

React

목록 보기
14/14

Scaling Up with Reducer and Context

Reducer: Component의 state update logic을 통합함.
Context: information을 아래 componenet로 전달함.

  • reducer만 사용하면, 해당 state를 사용하기 위해, 또 변경하기 위해서 state와 event handler를 props로 전달해야 함.
  • 프로젝트가 더 복잡해지고 깊어질수록, 이 형태는 좋지 않다.
  • 이 state와 dispatch를 Context로 만들면 해결 가능함.
  • prop drilling 없이, state를 읽고, dispatch로 변경할 수 있음.
  1. Context 생성
  2. Context에 state, dispatch 넣기
  3. 하위 컴포넌트에서 useContext로 사용

0. 새로운 stateProvider Component 생성

  • 새로 파일을 만들기.
// stateProvider.js

export function StateProvider() {
  return ();
}

1. Context 생성

// stateProvider.js

import { createContext } from 'react';

export const StateContext = createContext();

export function StateProvider() {
  return ();
};

2. Context에 state, dispatch 넣기

// StateProvider.js

import { createContext, useReducer } from 'react';

const reducer = (state, action) => {
  switch (action.type) {
      ...
  }
};
  
export const StateContext = createContext();

export function StateProvider() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return ();
};

3. provider로 감싸서 stateProvider 완성하기

// StateProvider.js

import { createContext, useReducer } from 'react';

const reducer = (state, action) => {
  switch (action.type) {
      ...
  }
};
  
export const StateContext = createContext();

export function StateProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StateContext.Provider value={{ state, dispatch }}>
        {children}
    </StateContext.Provider>);
};

4. 부모 컴포넌트를 Provider Component로 감싸기

// ParentComponent.js

import { StateProvider } from './StateProvider.js';
import ChildComponent from './ChildComponent.js';

export default function ParentComponent() {
  return (
    <StateProvider>
      <ChildComponent />
    </StateProvider>
  );
}

5. 하위 컴포넌트에서 useContext로 사용

// ChildComponent.js

import { useContext } from 'react';
import { StateContext} from './StateProvider.js';

export default function ChildComponent() {
  const { state, dispatch } = useContext(StateContext);
  
  ...
  
  return (
    ...
  );
}
  • context와 reducer가 모두 하나의 파일에 정의되어 있음.
  • 데이터를 어디에서 가져오는지에 대한 고민을 덜고, 어떻게 보여줄지에 대해 집중할 수 있게 됨.
  • stateProvider Component의 모든 자식 Component에서 해당 state를 공유함.
  • 어느 자식에서든 useContext(StateContext)로 state, dispatch 사용이 가능함.
  • state로 데이터를 읽고, dispatch로 데이터를 변경할 수 있음.

출처

https://react.dev/learn/passing-data-deeply-with-context

profile
handsome

0개의 댓글