[TIL] React Native에서 useReduce 실습 <1>

Simple Key·2020년 6월 8일
0
post-thumbnail

1. useState를 활용한 컴포넌트

// CountScreen 컴포넌트 !
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

const CounterScreen = () => {
  const [count, setCount] = useState(0);
  
  return (
    <View>
      <Text>현재 숫자 : {count}</Text>
      <Button title='INCREASE' onPress={()=>setCount(count + 10)} />
      <Button title='DECREASE' onPress={()=>setCount(count - 10)} />
    </View>
  )
}

export default CounterScreen;

⬆︎ useState 를 사용하여 만든 간단한 컴포넌트!
이 컴포넌트를 useReducer 를 사용하여 state 관리를 해보았다.
(물론 이러한 간단한 컴포넌트는 굳이 useReducer 를 사용할 필요는 없음)


2. useReducer로 바꿔보기

//1. 먼저 useReducer를 'react'에서 import 하기!
import React, { useReducer } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

// 2. 함수형 컴포넌트 밖에서 reducer() 함수 정의하기!
// 2-1. reducer 함수는 useReducer()의 첫번째 인자로 사용됩니다.
// 2-2. reducer의 인자1, 인자2는 통상적으로 state, action으로 씀!
const reducer = (state, action) => {
  // 2-3. state 는 현재 state! 예) {count : 0}
  // 2-4. action은 객체 형태! 예) {type: 'increment', payload : 10}
  switch(action.type){
    case increment:
      return {...state, count: state.count + action.payload};
    case decremnet:
      return {...state, count: state.count - action.payload};
    default :
      return state;
  }
};

// CounstScreen 컴포넌트 시작
const CounterScreen = () => {
  //3. useReducer 선언! useReducer 인자1은 reducer, 인자2는 state초기값
  const [state, dispatch] = useReducer(reducer, {number : 0});
  const {count} = state; // <-- 비구조화 할당
  
  //3-1. action 객체를 변수로 지정 ( 변수 지정 안하고 직접 dispatch에 써도 됨 )
  //3-2. action은 객체이기 때문에 문자열은 꼭 ''안에 쓰는 것 잊지 말기!  
  const increaseState = { type:'increment', payload: 10 };
  const decreaseState = { type:'decrement', payload: 10 };
 
  
  return(
    <View>
      <Text>현재 숫자 : {count}</Text>
      // 4. 이벤트에 dispatch함수를 실행시킨다. 인자로는 action 객체를 넣는다.
      <Button 
        title='INCREASE' 
        onPress={()=>dispatch(increaseState)} 
      />
      <Button 
        title='DECREASE' 
        onPress={()=>dispatch(decreaseState)} 
      />
    </View>
  )
}

※ 참고

reducer 함수 내 switch 에서 사용한 전개연산자(...)에 대하여..

{...state, count : state.count + action.payload}
⬆︎reducer 함수 리턴하고 있는 이 객체를 보면 맨 앞에 ...state라는게 있다.

😮;; 이거시 대체 무엇이요 ..?

이 컴포넌트 state 는 객체 형태이다. 예) {count : 0}

swtich 조건문을 사용하여 조건에 부합했을때 저 위 객체를 리턴하는 것인데, 이 객체안에 ...state라고 쓰는 이유는??

state 객체가 단순히 {count : 0}가 아니라 만약
{count : 0, color: 'blue', name: 'simplekey'}로 상태가 여러개일때 ...state로 state 객체의 프로퍼티들을 가져올 수 있다.

{ count:0, color: 'blue', name: 'simplekey' }를
{...state, count : 500}이라고 하면
⬇︎⬇︎⬇︎ count 만 덮어쓰기
{ count:500, color: 'blue', name: 'simplekey' }


useReduce 를 사용하면 상태값(state)를 객체형태로 관리하기 때문에 ...state식의 전개연산자(spread operator)가 유용하다!

profile
프론트엔드 개발자 심기현 입니다.

0개의 댓글