본문 바로가기
seungchan.dev
뒤로

useReducer로 +1, -1 카운터 만들기

INCREMENT·DECREMENT 액션을 처리하는 reducer를 useReducer에 넘겨 +1, -1 버튼으로 숫자를 바꾸는 카운터를 만들었습니다.

1분 읽기#React

2023년에 쓴 글이라 지금과 다른 내용이 있을 수 있습니다.

useReducer를 사용해 보려고 간단하게 -1, +1 버튼을 구현해 봤다.

javascript
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;
  }
}
 
function Counter() {
  const [number, dispatch] = useReducer(reducer, 0);
 
  const onIncrease = () => {
    dispatch({ type: "INCREMENT" });
  };
 
  const onDecrease = () => {
    dispatch({ type: "DECREMENT" });
  };
 
  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-11</button>
    </div>
  );
}
 
export default Counter;