IT/Node.js

useState Vs useReducer

밍띠이 2023. 10. 6. 22:26
반응형

useState

- 새로운 State를 생성

State를 업데이트 시키는 함수 제공

> 컴포넌트 내부에 State 관리 로직을 작성해야함

// use useState 방식
import { useState } from "react";

export default function A(){
    const [count, setCount] = useState(0);

    const onDecrease = () => {
        setCount (count - 1);
    } 
    const onIncrease = () => {
        setCount (count + 1);
    }
    return (
        <div>
            <h4>{count}</h4>
            <div>
                <button onClick={onDecrease}>-</button>
                <button onClick={onIncrease}>+</button>
            </div>
        </div>
    );
}

useReducer

- 새로운 State를 생성 (동일)

- State를 업데이트 시키는 함수 제공( 동일)

> 컴포넌트 외부에 State 관리 로직 분리 가능

// use useReducer 방식
import { useReducer } from "react";


function reducer(state, action) {
    if(action.type === "DECREASE"){
        return state - action.data;
    }
    else if(action.type === "INCREASE"){
        return state + action.data;
    }
}

export default function B(){
    const [count, dispatch] = useReducer(reducer, 0);
    return (
        <div>
            <h4>{count}</h4>
            <div>
                <button 
                onClick={() => {
                    dispatch({
                        type: "DECREASE",
                        data: 1,
                    });
                }}>-</button>
                <button 
                onClick={() => {
                    dispatch({
                        type: "INCREASE",
                        data: 1,
                    });
                }}>+</button>
            </div>
        </div>
    );
}

 

reducer(state, action){}

형식으로 반환하여, 해당 정보를 주고받을 수 있다.

 

반응형