본문 바로가기
컴퓨터/CSR (React, Vue)

[React] useReducer 뜻과 의미, 완전쉽게 사용해보기😃

by 버니케이 2023. 6. 10.
반응형

 

useReducer 

useState 대체 훅 입니다.

useState 로는 보통 숫자형 문자열 같은 간단한 데이터를 관리하는데 반해

useReducer 는 객체 같은 복잡한 데이터를 관리합니다. 

 

 

저도 예전에 회원정보 관리할때 로그인 상태를 관리하기 위해서 useReducer 를 사용했는데

처음에 익힐때는 어려웠지만 한번 써보니까 굉장히 편하더라구여

 

 


useReducer 사용해보기

 

버튼 눌렀을 때 값을 증가/감소 시키는 로직을 useReducer 훅을 사용해서 짜왔습니다.

/* eslint-disable */
import { useReducer } from 'react'

export default () => {

    const initialState = { count: 0 };


    function reducer(state, action) {

        console.log('모지',action);
        console.log('모지바꿀객체',state);

        switch (action.type) {
            case "증가":
            return { count: state.count + action.data };
            case "감소":
            return { count: state.count - action.data };
            default:
            throw new Error("오잉", action.type);
        }
    }

    const [state, dispatch] = useReducer(reducer, initialState);

    return(
        <>
            <h2>{state.count}</h2>
            <button onClick={() => dispatch({ type: "증가", data: 1 })}>
                증가
            </button>
            <button onClick={() => dispatch({ type: "감소", data: 1 })}>
                감소
            </button>
        </>
    )
}

 

 

근데 영어로 되어있으니까 어렵잖아요

그래서 제가 한글로 바꿔봤습니다. 

코딩애플님 강의 듣다보니까 한글로 이름짓는게 익숙해져버렸어용...

 

/* eslint-disable */
import { useReducer } from 'react'

export default () => {

    const 처음객체 = { count: 0 };


    function 객체바꿔주는함수(바꿀객체, 인자로받아온객체) {

        console.log('모지',인자로받아온객체);
        console.log('모지바꿀객체',바꿀객체);

        switch (인자로받아온객체.type) {
            case "증가":
            return { count: 바꿀객체.count + 인자로받아온객체.data };
            case "감소":
            return { count: 바꿀객체.count - 인자로받아온객체.data };
            default:
            throw new Error("오잉", 인자로받아온객체.type);
        }
    }

    const [바꿀객체, 객체넘겨주는함수] = useReducer(객체바꿔주는함수, 처음객체);
    
    return(
        <>

            <p>{바꿀객체.count}</p>
            <button onClick={() => 객체넘겨주는함수({ type: "증가", data: 1 })}>
                증가
            </button>
            <button onClick={() => 객체넘겨주는함수({ type: "감소", data: 1 })}>
                감소
            </button>
        </>
    )
}

 


설명

 

1. useReducer 훅

// useReducer 훅
const [state, dispatch] = useReducer(reducer, initialState);
const [바꿀객체, 객체넘겨주는함수] = useReducer(객체바꿔주는함수, 처음객체);

 

useState 처럼 distructuring 으로 되어있습니다.

안에 state, dispatch 라는 애들이 들어가는데

state 는 바꿀 객체, dispatch 는 객체를 넘겨주는 함수 입니다.

 

useReducer 훅의 인자는

reducer, initialState 가 들어가는데

reducer 는 객체의 값을 바꿔주는 함수, initialState 는 객체의 초기값입니다.

 

 

 

2. 선언되는 변수 (state, dispatch)

// variable
const initialState = { count: 0 };
const 처음객체 = { count: 0 };

 

initialState 는 말 그대로 초기 객체값 입니다.

변수 선언 + 할당하듯이 해주는 겁니다.

지금은 count 키값을 0 으로 세팅해놨습니댱

 

// function
function reducer(state, action) {

    console.log('모지',action);
    console.log('모지바꿀객체',state);

    switch (action.type) {
        case "증가":
        return { count: state.count + action.data };
        case "감소":
        return { count: state.count - action.data };
        default:
        throw new Error("오잉", action.type);
    }
}

function 객체바꿔주는함수(바꿀객체, 인자로받아온객체) {

    console.log('모지',인자로받아온객체);
    console.log('모지바꿀객체',바꿀객체);

    switch (인자로받아온객체.type) {
        case "증가":
        return { count: 바꿀객체.count + 인자로받아온객체.data };
        case "감소":
        return { count: 바꿀객체.count - 인자로받아온객체.data };
        default:
        throw new Error("오잉", 인자로받아온객체.type);
    }
}

reducer 함수는 받아온 객체를 바탕으로 값을 바꿔주는 함수입니다.

state 는 바꿀 객체 값입니다. 

action 은 인자로 받아온 객체인데,

이 인자로 받아온 객체의 상태에 따라서 객체의 값을 바꿔줍니다.

 

그니까...

이렇게 됩니다.

 

 

3. 파라미터


return(
    <>
        <h2>{state.count}</h2>
        <button onClick={() => dispatch({ type: "증가", data: 1 })}>
            증가
        </button>
        <button onClick={() => dispatch({ type: "감소", data: 1 })}>
            감소
        </button>
    </>
)

return(
    <>

        <p>{바꿀객체.count}</p>
        <button onClick={() => 객체넘겨주는함수({ type: "증가", data: 1 })}>
            증가
        </button>
        <button onClick={() => 객체넘겨주는함수({ type: "감소", data: 1 })}>
            감소
        </button>
    </>
)

dispatch 함수 / 객체넘겨주는함수

파라미터를 살펴봅시당

와 엄청 직관적이다 그져

 

 

 


 

 

 

+그와중에 요즘 ai 폼 미쳤네여

짜고싶은 코드 다 알려줌...ㅎㅎㅎ

반응형

댓글