REACT_Context 2. useReducer 예제

Eunsu·2021년 11월 28일
0

@ FLUX(context,redux)

목록 보기
3/5
post-thumbnail

예제를 만드려고 준비하다 보니까 useReducer가 도저히 이해가 안감..,,
다시공부하려고 함,, 왜냐면 useReducer를 사용하면 컴포넌트의 상태 업데이트 로직을 컴포넌트로부터 분리시킬 수 있다. 그래서 context를 사용해 전역으로 state를 사용할 경우 useReducer를 사용하면 편리하게 state 여러개를 컴포넌트로 보내줄 수 있는데 사용법을 모르겠음,, ㅜㅜ 그래서 예제를 쫌 보려고 함,,

우선 저번 포스팅에서도 설명했는데, useReducer란?

useReducer란?

🔹 useReducer 기본 구조

const [state,dispatch]= useReducer(reducer, initialState);
  • State : 우리가 앞으로 컴포넌트에서 사용할 수 있는 상태
  • Dispatch : 액션을 발생시키는 함수

▪️reducer함수는 현재 상태객체와 행동객체 (state , action)를 인자로 받아서 새로운 상태 객체를 반환하는 함수이다.
▪️ dispatch함수는 컴포넌트 내에서 상태변경을 일으키기 위해서 사용되는데 인자로 reducer 함수에 넘길 action을 받는다.

한마디로 말해, 컴포넌트에서 dispatch함수에게 action을 던지면, reducer 함수가 이 action에 따라 state를 변경해준다.

아 어렵,, 이제 쫌 이해감

◼️ 나의 생각정리 reducer

const [state,dispatch]= useReducer(reducer,initialValue)
  1. reducer 함수만들기. action type을 정하고, type에 따라 변화하거나 처리해야할 setState를 만듬. 이게 reducer 함수임.

  2. 여기서 사용하게 될 state임.

  3. dispatch는 컴포넌트에서 사용할 action 변화 함수임.

◼️ 이거 왜 씀?

context나 redux처럼 프로젝트의 규모가 커져 전역으로 사용할 state가 필요할 경우, 단일방향으로 prop을 전달해줘야 함. useState를 사용하고, setState를 사용하기에는 한계가 있고, state를 많이 만들어야 함.

useReducer를 사용하면 상태 업데이트로직을 컴포넌트로 분리시킬 수 있다. 그럼 관리하기 더 편해지고 props 전달 구조도 조금 더 깔끔하게 관리할 수 있다.

전역 state를 사용하면 이 state를 관리해야 하는데, 그때 useReducer를 사용하면 분리된 컴포넌트에서 쉽게 상태관리를 할 수 있음.

🔹 useReducer Example

◼️ Counter.js

  1. reducer 함수 만들기
//Counter.js

function reducer(state,action){
	switch(action.type){
      case "INCREASE" : 
        return state+1;
      case "DECREASE" : 
        return state -1;
      default : return state;
    }
}

const Counter =() => {
	return <div>
      <h1> This is Number </h1>
  	<button>Increase</button>
  <button>Decrese</button>
      </div>
}

reducer는 action을 변화시키는 함수이다. 이 리액트 페이지는 버튼을 누르면 1 이 증가하고, decrease를 누르면 1이 감소한다.

acion의 type을 받아 switch문으로 처리해준다.
type의 값을 대문자와 _로 구성하는 관습이 존재하기도 하지만 꼭 따를 필요는 없음.

잊지말자 . reducer는 action 의 변화를 나타내는 함수이다.

  1. useReducer()
//Counter.js
function reducer(state,action){
	switch(action.type){
      case "INCREASE" : 
        return state+1;
      case "DECREASE" : 
        return state -1;
      default : return state;
    }
}
const Counter =() => {
  const [number,dispatch]= useReducer(reducer,0);
	return <div>
      <h1> This is Number </h1>
  	<button>Increase</button>
  <button>Decrese</button>
      </div>
}
  • number : state name
  • dispatch : 컴포넌트와 reducer를 연결하는 함수
  • reducer : action 함수
  • 0 : initial value
  1. onIncrease, onDecrease
//Counter.js
function reducer(state,action){
	switch(action.type){
      case "INCREASE" : 
        return state+1;
      case "DECREASE" : 
        return state -1;
      default : return state;
    }
}
const Counter =() => {
  const [number,dispatch]= useReducer(reducer,0);
  const onIncrease =() => dispatch({type:"INCREASE"})
  const onDecrease =() => dispatch({type:"DECREASE"})
	return <div>
      <h1> {number}</h1>
  	<button onClick={onIncrease}>Increase</button>
  <button onClick={onDecrease}>Decrese</button>
      </div>
}

dispatch함수로 reducer를 연결시켜 함수를 만들고, element에 적용시키면 된다.

한 50% 이해감. 다음에는 Context와 useReducer를 사용해 전역에서 state 관리하는 예제를 만들꺼임

오늘 비루개카페왔는데 풀속에서 공부잘하구감 쮸앙!

profile
function = (Develope) => 'Hello World'

0개의 댓글