공부/React

[ React-Hooks ] useReducer 사용하기

신입개발자 2021. 6. 25. 06:12

useReducer 선언하기

// 1 카운터 구현하기
function reducer(state, action){
  // action.type에 따라 다른 작업 수행
  switch (action.type){
    case 'INCREMENT' :
      return { value : state.value + 1};
    case 'DECREMENT' :
      return { value : state.value -1};
    default:
      // 아무것도 해당되지 않을 때 기존 상태 반환
      return state;
  }
}
// 2 인풋 상태 관리하기
function reducer(state, action) {
  return {
    ...state,
    [action.name] : action.value
  };
}

1. useReducer 카운터

App.js

import React from "react";
import Counter from "./hooks/Reducer";

function App() {
  return (
    <div>
      <Counter />
    </div>
  );
}

export default App;

Reducer.js

import React,{useReducer} from "react";

function reducer(state, action){
  // action.type에 따라 다른 작업 수행
  switch (action.type){
    case 'INCREMENT' :
      return { value : state.value + 1};
    case 'DECREMENT' :
      return { value : state.value -1};
    default:
      // 아무것도 해당되지 않을 때 기존 상태 반환
      return state;
  }
}

const Counter = () => {
  const [state, dispatch] = useReducer(reducer, { value : 0});

  return (
    <div>
      <p>
        현제 카운터 값은 <b>{state.value}</b> 입니다.
      </p>
      <button onClick={() => dispatch({ type: 'INCREMENT'})}>+1</button>
      <button onClick={() => dispatch({ type: 'DECREMENT'})}>-1</button>
    </div>
  );
};
export default Counter;

실행화면


2. 인풋 상태 관리하기

Reducer2.js

import React,{useReducer} from "react";

function reducer(state, action) {
  return {
    ...state,
    [action.name] : action.value
  };
}

const Reducer2 = () => {
  const [state, dispatch] = useReducer(reducer,{
    name: '',
    nickName: '',
});
  const { name, nickname } = state;
  const onChange = e => {
    dispatch(e.target);
  };

  return (
    <div>
      <div>
        <input name='name' value={name} onChange={onChange}/>
        <input name='nickname' value={nickname} onChange={onChange}/>
      </div>
      <div>
        <div>
          <b>이름</b> {name}
        </div>
        <div>
          <b>닉네임</b> {nickname}
        </div>
      </div>
    </div>
  );
};

export default Reducer2

실행화면


useReducer에서의 액션은 그 어떤 값도 사용 가능합니다 그래서 이번에는 이벤트 객체가 지니고 있는 e.target 값 자체를 액션 값으로 사용했습니다 이런 식으로 인풋을 관리하면 아무리 인풋 개수가 많아져도 코드를 짧고 깔끔하게 유지할 수 있습니다