프론트엔드/React

useReducer로 상태 관리

짱뚱짱 2024. 9. 19. 16:19

📢 useReducer : 요청 상태에 따라 관리하기.

  - react의 고급기술인 리덕스에서 자주 사용.

 

  - 기본구조

const reducer = (state, action) => {
    switch(action.type) {
        case "INCREMENT":
            return state + 1;
        case "DECREMENT":
            return state - 1;
        default:
            return state;
    }
}

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

//state : 현재 상태 값 => 변수
//action : dispatch 함수로 받을 액션
//dispatch  : state 값을 업데이트 하고, 재렌더링을 촉발하는 함수

  

📢 실습

  - 카운터 컴포넌트 구현 예제

//Comp2.jsx
import React from 'react';
import './comp.css';
import Counter from './Counter';
import Input from './Input';
import Color from './Color';
import Input2 from './Input2';
import Counter2 from './Counter2';


const Comp2 = () => {

    return (
        <div className='comp2'>
            <div>Comp2 영역입니다.</div>

            <Counter2 />
            <hr />
            <Counter />
            <hr />
            <Input />

            <hr />
            <Color />

            <hr />
            <Input2 />
        </div>
    );
};

export default Comp2;
//Counter2.jsx
import React from 'react';
import { useReducer } from 'react';

function reducer(state, action){
    switch(action.type) {
        case "INCREMENT":
            return state + 1;
        case "DECREMENT":
            return state - 1;
        default:
            return state;
    }
}

//위와 같음
// const reducer = (state, action) =>{

// }

const Counter2 = () => {

    const [ count, dispatch ] = useReducer(reducer, 0);

    const increment = () => {
        dispatch({ type : "INCREMENT"});
    }

    return (
        <div className='counter2'>
            <h1>{count}</h1>
            <button onClick={increment}>+</button>
            <button onClick={ ()=>{dispatch({ type: "DECREMENT" })} }>-</button>
        </div>
    );
};

export default Counter2;

 

  - 결과