React Hooks - useReducer

jh22j9·2020년 10월 12일

React Hooks

목록 보기
1/3

useReducer


useReducer is a hook that is used for state management. useReducer is related to reducer function.

useReducer를 이해하기 위해 근간이 되는 개념인 reducer 함수를 공유하는 JS의 reduce method와 비교하며 짚어본다.

reduce vs useReducer

Reduce in JavaScriptuseReducer in React
array.reduce(reducer, initialValue)useReducer(reducer, initialState)
singleValue = reducer(accumulator, itemValue)newState = reducer(currentState, action)
reduce method returns a single valueuseReducer returns a pair of values [newState, dispatch]
  • action parameter is what dictates the state transition from the current state to the new state.
  • dispatch method is basically used to specify the action.
  • useReducer will accept two parameters, a reducer function and the initialState. The reducer function also accepts two parameters which are the currentState and the action. Depending on the values of currentState and the action, the reducer function will return a newState. So useReducer is basically changing the state in react component.

useReducer 예시

import React, {useReducer} from 'react';

// (2) define reducer function and initialState outside the component
const initialState = 0; 
const reducer = (state, action) => {
  // reducer function accepts the (current) state and an action and returns the new state depending on the action. 
  // action is an instruction to the reducer function for the state transition.

  // the convention to execute codes based on action is to use switch statements.
  switch(action) { 
    // the switch expression is the action. 
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return initialState;
    default: 
      return state;
  }
}

function CounterOne() {
  // (1) call useReducer in the component
  // useReducer(reducer, initialState); - (3)으로 갱신하며 주석 처리 

  /* (3) get a value to display in the JSX, call the reducer function with the appropriate action. 
         useReducer returns a pair of values which we can get hold off using the array destructuring syntax. */
  const [count, dispatch] =  useReducer(reducer, initialState);
  // so useReducer returns the current state(value) which we have called as count paired with a dispatch method.
  // dispatch method allow to execute the code corresponding to a particular action. 

  return (
    <div>
      {/* (4) add div tag that displays count value */}
      <div>Count - {count}</div>

      {/* (5) add click handler to each button */}
      <button onClick={() => dispatch('increment')}>Increment</button>
      <button onClick={() => dispatch('decrement')}>Decrement</button>
      <button onClick={() => dispatch('reset')}>Reset</button>
      {/* the argument to the dispatch method is the action that is specified in the reducer function*/}
    </div>
  )
}

export default CounterOne

🔗 React Hooks Tutorial - 19 - useReducer (simple state & action) 👍

0개의 댓글