[React] Redux

young·2022년 7월 6일
0

6/23~7/20 Section 3 TIL

목록 보기
11/21

Before learn...

React -> state와 props를 이용한 컴포넌트 단위 개발 아키텍처
redux -> 컴포넌트와 상태를 분리하는 패턴을 익힌다.


✅ TIL

  • Redux
    Aciton, Dispatch, Reducer, Store

  • Redux Hooks
    useSelector, useDispatch

  • Redux 3가지 원칙




Redux

✔️ Redux

: 상태 관리 라이브러리
전역 상태 저장소 store를 제공한다.


단방향 데이터 흐름

Action -> Dispatch -> Reducer -> Store

  1. 상태 변경 이벤트가 발생하면,
    변경될 상태에 대한 정보가 담긴 action 객체가 생성된다.
  2. action 객체는 dispatch 함수의 인자로 전달된다.
  3. dispatch 함수는 action 객체를 reducer 함수로 전달한다.
  4. reducer 함수는 action 객체의 값을 확인하고, 전역 상태 저장소 store의 상태를 변경한다.
  5. 상태가 변경되면 react는 화면을 리렌더링한다.

Action

액션의 정보를 담은 객체
type: Action 객체가 어떤 동작을 하는지 나타낸다.

//Action
{ type: 'INCREASE'}


//Action Creater
const setNumber = num => {
  return {
    type: 'SET_NUMBER',
    payload: num,
  }
}

대문자, Snake Case로 작성한다.

액션 생성자 함수(Action Creater)를 만들어 사용하기도 한다.


Dispatch

Reducer로 Action을 전달해주는 함수
인자로 Action 객체 또는 Action Creater를 갖는다.

Reducer을 호출하는 역할을 한다.

dispatch( { type: 'INCREASE'} );

dispatch( setNumber(5) )

Reducer

Dispatch로부터 전달받은 Action 객체의 type에 따라서 상태를 변경시키는 순수 함수
외부 요인으로 인해 상태가 변경되는 일이 없어야 한다.

Reducer 함수의 리턴값이 새로운 state가 된다.

const reducer = (state, action) => {
  switch(action.type)
    case 'INCREASE' :
    	return state + 1
    case 'DECREASE' :
    	return state - 1
    
    //해당하는 case가 없을 시 기존 상태를 그대로 리턴한다.
    default: 
    	return state;   
}

switch, case: action 객체의 type에 따라 분기하는 조건문

Reducer 함수가 여러 개인 경우 Redux의 combineReducers method를 사용한다.

import { combineReducers } from 'redux';

const reducer = combineReducers({
  countReducer,
  ...
});

Store

상태가 관리되는 저장소

import { createStore } from 'redux';

const store = createStore(rootReducer);



Redux Hooks

'react-redux'에서 불러온다.

useSelector()

컴포넌트와 state를 연결하여 redux의 state에 접근할 수 있게 하는 hook

import { useSelector } from 'react-redux'

const counter = useSelector(state => state.counterReducer)

useDispatch()

action 객체를 reducer로 전달해주는 hook
dispatch 함수를 쓸 수 있게 한다.

import { useDispatch } from 'react-redux';

const dispatch = useDispatch()
dispatch( increase() )



Redux 3가지 원칙


1. Single source of truth

동일한 데이터는 항상 같은 곳에서 가져와야 한다.

Redux의 데이터 저장소는 store 단 하나이다.

2. State is read-only

상태는 직접 변경할 수 없다.

Action 객체가 있어야만 상태를 변경할 수 있다.

3. Changes are made with pure functions

변경(Reducer)은 순수 함수로만 가능하다.




Learn more...

https://www.robinwieruch.de/react-redux-tutorial/
https://facebook.github.io/flux/docs/in-depth-overview/

profile
즐겁게 공부하고 꾸준히 기록하는 나의 프론트엔드 공부일지

0개의 댓글