단순 코드 기록/React

React_useReducer_숫자 증감

일일일코_장민기 2024. 3. 18. 15:17
728x90

 

 

import { useReducer } from "react"
/*
  상태관리방법
  1. useState
  2. useReducer : 컴포넌트와 상태 업데이트 로직을 분리 가능하도록 구현할 수 있음
  - 아키택처:     액션 => reducer -> state -> 뷰(이벤트 발생)
    1) reducer는 현재 상태갑인 state와 action인자를 받아서 새로운 nextState값을 반환
        import{useReducer} from 'react';
        const reducer = (state, action) => {
          retrun nextState;
        }
    2) action의 형태(dispatch함수로 전달)
        {
          type: 'INCREMENT'
        }
        {
          type: 'CHANGE_INPUT',
          key: 'email',
          value: 'zzz@daum.net'
        }
        {
          type: 'ADD_TODO, todo: {
                  id:1,
                  pw:2
                }
        }
    3) 실제 사용 방법
        const [state, dispatch] = useReducer(reducer, initialState);
        const onIncrease = (){
          dispatch({type: 'INCREMENT'})
        }
*/



export default function App(){
  const reducer = (current_state, action) => {        //관리할 상태변수, 동작할 type
    switch (action.type) {
      case "INCREMENT":
        console.log("increment");
        return (current_state = current_state + 1);
      case "DECREMENT":
        console.log("decrement");
        return (current_state = current_state - 1);
      default:
        console.log("default")
        return current_state;
    }
  };

  const [number, dispatch] = useReducer(reducer, 0);   //순서 주의
  const onIncrease = () => {
    dispatch({ type: "INCREMENT"})
  }

  const onDecrease = () => {
    dispatch({ type: "DECREMENT"})
  }

  return(
    <>
      <div>
        <h1>{number}</h1>
        <button onClick={onIncrease}>+</button>
        <button onClick={onDecrease}>-</button>
      </div>
    </>
  )

}

 

'단순 코드 기록 > React' 카테고리의 다른 글

React_Context(Single/Multi)  (0) 2024.03.18
React_useReducer_글자  (0) 2024.03.18
React_useContext로 변수와 함수 전송  (0) 2024.03.18
React_useState를 활용한 Cart  (0) 2024.03.18
React_useContext Hook  (0) 2024.03.18