LoginSignup
0
0

More than 3 years have passed since last update.

reducer 사용하기

Posted at

reducer 를 사용해보기

import React,{useReducer} from 'react';

function reducer(state, action){
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;

        case 'DECREMENT':
            return state - 1;
        default:
            return state
    }
};

//useReducer 에 넣는 첫번째 파라미터는 reducer 함수이고, 두번째 파라미터는 초기 상태입니다.

function Counter(){
    const [number, dispatch] = useReducer(reducer, 0);

    const onIncrease = () => {
        dispatch({type : 'INCREMENT'})
    };
    const onDecrease = () => {
        dispatch({type : 'DECREMENT'})

    }
    return(
        <div>
            <h1>{number}</h1>
            <div>
                <button className="btn btn-light" onClick={onIncrease}>+1</button>
                <button className="btn btn-light" onClick={onDecrease}>-1</button>
            </div>
        </div>
    )
}

export default Counter;

reducer 는 상태를 관리해준다고 하는데
최근에는 reducer 를 사용하지 않고 mobx 로 한다고도 하는데 어찌되었든간에 연습해보았다.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0