TIL.React hooks_useReducer

chloe·2021년 3월 28일
0

TIL

목록 보기
64/81
post-thumbnail

useReducer

useReducer는 state관리에 사용되는 hook이다.
이 말은 즉 useState의 대안이 되기도 한다는 의미
그렇다면 useState vs useReducer는 무슨 차이를 가지는가?

useState는 useReducer를 사용해서 만들어진다. 그럼 언제 useReducer를 사용하고 언제 useState를 사용하는가?

Array.prototype.reduce()

reduce()메서드는 배열의 각 element에 있는 reducer 함수를 실행한다.

const array1=[1,2,3,4];
const reducer=(accumulator, currentValue)=>accumulator +currentValue;

console.log(array1.reduce(reducer));
1+2+3+4=10

console.log(array1.reduce(reducer,5));
//5+1+2+3+4 =15

reduce vs useReducer

reduce in Javascript

  • array.reduce(reducer, initialValue)
  • singleValue=reducer(accumulator,itemValue)
  • reduce method returns a single value
    useReducer in react
  • useReducer(reducer,initialState)
  • newState=reducer(currentState,action)
  • useReducer returns a pair of values.[newState,dispatch]

useReducer(simple state & action)

import React, {useReducer} from 'react'

const initialState=0

const reducer=(state,action)=>{
  switch(action){
  case 'increment':
     return state +1
  case 'decrement':
    return state -1
  case 'reset':
   return initialState
  default:
   return state
}
}

function CounterOne(){
  const [count,dispatch]= useReducer(reducer,initialState)
  useReducer는 2개의 값을 리턴할 수 있다. 현재 상태값은 count,dispatch는 action을 받아들여서 render function안에 명시된 코드를 실행할 수 있다
  
  return(
    <div>
    <div>Count - {count} </div>
     <button onClick={() =>dispatch('increment')}>Increment</button>
    <button onClick={() =>dispatch('decrement')}> Decrement</button>
    <button onClick={() =>dispatch('reset')}>Reset</button>
    </div>
    )
}
export default CounterOne

useReducer(complex state & action)

import React, {useReducer} from 'react'

const initialState={
  firstCounter:0
  secoundCounter:10
}
const reducer=(state,action_=>{
  switch (action.type){
    case 'increment':
      return {...state, firstCounter: state.firstCounter + action.value}
    case 'decrement':
      return  {..state, firstCounter: state.firstCounter -action.value}
      case 'increment2':
      return {...state, secondCounter : state.secondCounter + action.value}
    case 'decrement2':
      return  {...state,secondCounter : state.secondCounter -action.value}
    case 'reset':
      return initialState
    default:
      return state
  }
}
               
function CounterTwo(){
  const[count,dispatch]=useReducer(reducer,initialState)
  return(
    <div>
    <div> First Counter - {count.firstCounter}</div>     
<div> Second Counter - {count.secondCounter}</div>
    <button onClick={()=>dispatch({type:'increment', value:1})}> Increment</button>
 <button onClick={()=>dispatch({type:'decrement'})}> Decrement</button>
 <button onClick={()=>dispatch({type:'reset'})}> Reset</button>
<button onClick={()=>dispatch({type:'increment2', value:1})}> Increment Counter 2</button>
 <button onClick={()=>dispatch({type:'decrement2'})}> Decrement Counter 2</button>
</div>
)
}
export default ConterTwo
  
profile
Front-end Developer 👩🏻‍💻

0개의 댓글