FrontEngineer JungBam

useReducer 본문

리액트

useReducer

정밤톨 2022. 11. 24. 21:47

useState와 같이 상태관리를 하는 훅인 useReducer, 어떤 점에서 차이가 있는지 알아보자.

 

먼저, useReducer의 동작원리를 알아보자.

useReducer를 이해하기 위해 reducer 함수와 disPatch, action, state의 관계를 알아야 된다.

1. const [state, disPatch] = useReducer(reducer함수, 초기값)으로 선언된다.

2. const reducer = (state,action)=>{
   switch(action.type){
      case '1의 경우' :
         return 1의 경우의 결과값
      case '2의 경우' :
         return 2의 경우의 결과값
      default :
         return 기본으로 주는 결과값
   }
}
이런식으로 스위치문을 통해 acrion의 type에 따른 각각의 처리를 깔끔하게 할 수 있다.

3. disPatch(action)
이 action에 기본적으로 {type : '경우'}가 들어가고 어떠한 값을 전달할 때에는 {type:'경우', payload:'값'}의 형태로 작성하여 넘긴다.

4. 스냅샷으로 이 결과 값의 이전값과 결과값 이후의 값들을 저장하는 state가 되겠다.

※ disPatch 가 실행되면 reduce 함수가 실행되고 이때 action이 reducer에게 넘어가고 reducer가 작동한 결과값을 state가 저장한다.

 

 

기본적인 useReducer의 기능을 알아보기 위해 다시한번 생활코딩 영상을 찾아봤다.

참고 : https://www.youtube.com/watch?v=E7bNzWrlKTE 

 

useReducer와 useState의 가장 큰 차이는 useState는 state의 관리를 각자의 이벤트에서 한다고 생각하면 useReducer는 state 자체의 컨트롤은 reducer 함수에서 한다고 보면된다. 다른 예시들보다 위의 영상을 통해 카운터를 만들어보면 이해가 빠르다고 생각한다.


function reducer(oldState, action) {
  if (action.type === 'up') {
    return oldState + action.number
  } else if (action.type === 'reset') {
    return action.number
  } else if (action.type === 'down') {
    return oldState - action.number
  }
}
export default function App() {
  const [number, setNumber] = useState(1)
  const [count, countDisPatch] = useReducer(reducer, 0)

  const add = () => {
    countDisPatch({ type: 'up', number: number })
  }
  const zero = () => {
    countDisPatch({ type: 'reset', number: number })
  }
  const down = () => {
    countDisPatch({ type: 'down', number: number })
  }
  const changeNumber = (e) => {
    setNumber(Number(e.target.value))
  }
  return (
    <div>
      <input type="button" value="-" onClick={down}></input>
      <input type="button" value="0" onClick={zero}></input>
      <input type="button" value="+" onClick={add}></input>
      <input type="text" value={number} onChange={changeNumber} />
      <span>{count}</span>
    </div>
  )
}
 위의 코드는 생활코딩의 예제를 작성한 코드인데 이 코드를 분석함으로써 useReducer의 기능과 사용법을 알아보자.
먼저 useReducer는 앞서 이야기한대로 reducer함수를 통한 state 관리가 주요한 점인데 이 reducer함수는 사이드 이펙트로 컴포넌트 함수 안에서 선언되든 밖에서 선언되든 상관없다. 그럼 reducer 함수를 확인해보자. 보이는 바와 같이 countDisPatch의 인자를 객체로 주어 각각의 값으로 reduce 함수에서 동적인 변화를 줄 수 있다.
    countDisPatch({ type: 'up', number: number })

 

function reducer(oldState, action) {
  if (action.type === 'up') {
    return oldState + action.number
  } else if (action.type === 'reset') {
    return action.number
  } else if (action.type === 'down') {
    return oldState - action.number
  }
}
useReducer가 선언되는 방식은 useState와 비슷한 형태인데, 첫번째 인자로는 reducer 함수를, 두번째 인자로는 초기값을 받는다.

  const [count, countDisPatch] = useReducer(reducer, 0)

 

state에 따른 변화가 일정한 패턴을 그릴 때 재사용성이 용이하여 사용해볼 수 있을 것 같다.
반응형

'리액트' 카테고리의 다른 글

useContext  (1) 2022.11.27
리액트 훅과 렌더링  (0) 2022.11.26
useEffect를 이용한 debounce, throttle 처리  (0) 2022.11.24
LocalStorage와 useEffect  (0) 2022.11.23
useRef (feat. useState)  (0) 2022.11.23
Comments