기록

Context API (#2 심화)

안녕하세요 청이 입니다.

react Context에 대하여 조금더 심도있게 정리한 블로그 글을 보고 개인적으로 적용하며 정리한 글 입니다.

기본 코드는 #1 기초 에서 작성된것으로 시작 합니다.

Context를 많은 컴포넌트에서 사용한다면 하나의 훅으로 만들어 반환하는것이 좋습니다.

import React, {useContext} from 'react';
import {ColorContext} from "../contexsts/color";

const UseColorsState = () => {
    const value = useContext(ColorContext)
    return value
};

export default UseColorsState;

// ColorContext

import React, {createContext, useMemo, useState} from 'react';

export const ColorContext = createContext({
    counter: 0,
    actions: {
        increase: () => {},
        decrease: () => {},
    },
});

interface ColorProviderProps {
    children: React.ReactNode
}

export const ColorProvider = ({ children }:ColorProviderProps) => {
    const [counter, setCounter] = useState(0);
    const actions = useMemo(
        () => ({
            increase() {
                setCounter((prev) => prev + 1);
            },
            decrease() {
                setCounter((prev) => prev - 1);
            }
        }),
        []
    );

    const value = useMemo(() => ({ counter, actions }), [counter, actions]);

    return (
        <ColorContext.Provider value={value}>
            {children}
        </ColorContext.Provider>
    )
};

// ContextHook

import React from 'react';
import UseColorsState from "./hook/useColorsState";
const ContextHook = () => {
    const {counter, actions} = UseColorsState()

    return (
        <div>
            {`Hook : ${counter}`}
            <button style={{margin:'20px', width:'100px', height:'20px'}} onClick={()=>actions.increase()}>
                Increase
            </button>    <button style={{margin:'20px', width:'100px', height:'20px'}} onClick={()=>actions.decrease()}>
                Decrease
            </button>
        </div>
    );
};

export default ContextHook;

#1 기초와 달리 추가된 내용은 아래와 같습니다.
useMemo : 상태가 변경될떄 마다, useContext의 값을 새로 생성함으로, useMemo를 통해 방지 해줍니다.


저장소 (Context) 의 값이 자주 변경되는 경우 value, action을 분할 하자 !

분할하기 위해 value, action 으로 나누고 action에 대한 hook을 만듭니다.

또한 렌더링 되는 컴포넌트를 분할해 줍니다.

// ColorContext Store (Value, Action)

import React, {createContext, useMemo, useState} from 'react';

export const ColorContextValue = createContext(0);

export const ColorContextAction = createContext({
        increase: () => {},
        decrease: () => {},
});

interface ColorProviderProps {
    children: React.ReactNode
}

export const ColorProvider = ({ children }:ColorProviderProps) => {
    const [counter, setCounter] = useState<number>(0);
    const actions = useMemo(
        () => ({
            increase() {
                setCounter((prev) => prev + 1);
            },
            decrease() {
                setCounter((prev) => prev - 1);
            }
        }),
        []
    );

    return (
        <ColorContextAction.Provider value={actions}>
        <ColorContextValue.Provider value={counter}>
            {children}
        </ColorContextValue.Provider>
        </ColorContextAction.Provider>
    )
};

// ColorsActions

import React, {useContext} from 'react';
import {ColorContextAction} from "../contexsts/color";

const UseColorsActions = () => {
    return useContext(ColorContextAction)
};

export default UseColorsActions;

// ColorsValues

import React, {useContext} from 'react';
import {ColorContextValue} from "../contexsts/color";

const UseColorsValues = () => {
    return useContext(ColorContextValue)
};

export default UseColorsValues;

//ContextHook

import React from 'react';
import UseColorsActions from "./hook/useColorsActions";
const ContextHook = () => {
    const {increase, decrease}=UseColorsActions()

    return (
        <div>
            <button style={{margin:'20px', width:'100px', height:'20px'}} onClick={()=>increase()}>
                Increase
            </button>
            <button style={{margin:'20px', width:'100px', height:'20px'}} onClick={()=>decrease()}>
                Decrease
            </button>
        </div>
    );
};

export default ContextHook;

//ContextCount

import React from 'react';
import UseColorsValues from "./hook/useColorsValues";

const ContextCount = () => {
    const counter = UseColorsValues()

    return (
        <div>
            {`Counter : ${counter}` }
        </div>
    );
};

export default ContextCount;

// App

import React from 'react';

import ContextHook from "./ContextHook";
import {ColorProvider} from "./contexsts/color";
import ContextCount from "./ContextCount";

function App() {
  return (
      <ColorProvider>
            <ContextCount/>
            <ContextHook/>
      </ColorProvider>
  );
    }

export default App;

이렇게 하면, 카운터 값이 변경 되어도,
버튼 컴포넌트는 재 렌더링을 하지 않아 불필요한 메모리 누수를 방지 할수 있습니다.

여기까지 하면, context 를 통해서, 다양한 값을 저장하고 사용하는것에 문제가 없는듯 합니다.

하단의 참고한 블로그중 김민준님의 포스팅을 꼭 한번 읽어 보시길 추천드립니다.


댓글

이름만 적고 남길 수 있어요