[React] 상태관리 (useState / useReducer)

2022. 6. 24. 09:44·Stack/React

useState (값만 관리)

const [ state, setState] useState(초기값)

setState(state + 1)

ex> const [ number, setNumber ] = useState(0)

 

Counter2.js (useState 버전)

import React, { useState } from 'react';

const Counter2 = (props) => {
    // let number = 0;
    const [ number, setNumber ] = useState(0);   // 기본값은 0이다 
    function Increase() {
        setNumber(number+1);
    }
    function Decrease() {
        setNumber(number-1);
    }
    return (
        <div>
            <h2>{number}</h2>
            <button onClick={Decrease}>-1</button>
            <button onClick={Increase}>+1</button>
        </div>
    );
};

export default Counter2;

 

 

 

useReducer (값이 변경될 때 다른 것 처리도 가능)

import { useReducer } from 'react'

const [ state, dispatch ] = useReducer(함수, 초기값)

ex> const [ state, dispatch ] = useReducer(reducer, 0)

dispatch({ type: "INCREASE" })   // dispatch는 액션을 전달

function reducer(state, action) {

                switch (action.type) {

                case 'INCREASE':

                return state+1;

                case 'DECREASE':

                return state-1;

                }

}

 

Counter2.js (useRecucer 버전)

import React, { useReducer } from 'react';
function reducer(state, action) {
    switch(action.type) {
        case "INCREASE":
            return state +1;
            case "DECREASE":
            return state-1;
            default:
            return state;
    }
}

const Counter2 = (props) => {
    // let number = 0;
    const [ number, dispatch ] = useReducer(reducer, 0);   // 기본값은 0이다 
    function Increase() {
        dispatch({type: "INCREASE"});
    }
    function Decrease() {
        dispatch({type: "DECREASE"});
    }
    return (
        <div>
            <h2>{number}</h2>
            <button onClick={Decrease}>-1</button>
            <button onClick={Increase}>+1</button>
        </div>
    );
};

export default Counter2;

'Stack > React' 카테고리의 다른 글

[React] mashup-to-do list (useReducer + Context API)  (0) 2022.06.27
[React] Context API  (0) 2022.06.27
[React] React Component Styling  (0) 2022.06.23
[React] to-do list  (0) 2022.06.22
[React] 라이프 사이클 메서드(Life Cycle Method)  (0) 2022.06.21
'Stack/React' 카테고리의 다른 글
  • [React] mashup-to-do list (useReducer + Context API)
  • [React] Context API
  • [React] React Component Styling
  • [React] to-do list
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[React] 상태관리 (useState / useReducer)
상단으로

티스토리툴바