본문 바로가기
React

[Hooks] 3 : useReducer

by 바나냥 2020. 8. 26.

기본

const [state, dispatch] = useReducer(reducer, initialArg, init);

const result = () => {
    dispatch(action);
}

 

 

reducer는 현재 상태, 그리고 업데이트를 위해 필요한 정보를 담은 action 값을 전달받아 새로운 상태를 반환하는 함수입니다.

useReducer의 첫 번째 파라미터에는 reducer 함수를 넣고, 두 번째 파라미터에는 해당 reducer의 기본값을 넣어 state 값과 dispatch 함수를 받아와서 dispatch(action)과 같은 형태로 action 값을 넣어주면 reducer 함수가 호출되는 구조입니다.

 

 

useReducer vs useState

useReducer는 useState보다 더 다양한 컴포넌트 상황에 따라 다양한 상태를 다른 값으로 업데이트할 때 사용하는 Hook입니다.

 

import React, { useState } from 'react';
 
const Counter = () => {
  const [count, setCount] = useState(0);
 
  const handleIncrease = () => {
    setCount(count => count + 1);
  };
 
  const handleDecrease = () => {
    setCount(count => count - 1);
  };
 
  return (
    <div>
      <h1>Counter with useState</h1>
      <p>Count: {count}</p>
 
      <div>
        <button type="button" onClick={handleIncrease}>
          +
        </button>
        <button type="button" onClick={handleDecrease}>
          -
        </button>
      </div>
    </div>
  );
};
 
export default Counter;

 

import React, { useReducer } from 'react';

const initialState = { count: 0 };

const counterReducer = (state, action) => {
	switch (action.type) {
    	case 'INCREASE':
        	return { ...state, count: state.count + 1 };
    	case 'DECREASE':
        	return { ...state, count: state.count - 1 };
        default:
            throw new Error();
    }
}

const Counter = () => {
	const [state, dispatch] = useReducer(counterReducer, initialState);
    
    const handleIncrease = () => {
    	dispatch({ type: 'INCREASE' });
    }
    
    const handleDecrease = () => {
    	dispatch({ type: 'DECREASE' });
    }
    
    return (
    	<div>
        	<h1>Counter with useReducer</h1>
            <p>Count: {state.count}</p>

            <div>
              <button type="button" onClick={handleIncrease}>
                +
              </button>
              <button type="button" onClick={handleDecrease}>
                -
              </button>
            </div>
          </div>
    );
};

export default Counter;

 

 

 

 

 

 

https://ko.reactjs.org/docs/hooks-reference.html#usereducer

 

Hooks API Reference – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

https://www.robinwieruch.de/react-usereducer-vs-usestate

 

useReducer vs useState in React - RWieruch

Comparing useState and useReducer in React, when to use them for different use cases, and their benefits in a growing React application ...

www.robinwieruch.de

 

'React' 카테고리의 다른 글

숫자만 입력 가능하게 하기  (0) 2020.08.31
Styled-Components (& ~ &, & + &)  (0) 2020.08.27
[Hooks] 2 : useEffect  (0) 2020.08.26
setUrl / handleUrl  (0) 2020.08.26
[React 스터디] 2 : 접근성  (0) 2020.08.21

댓글