[06] React - Redux

HJ-C·2022년 7월 31일

React

목록 보기
6/7
post-thumbnail

Redux

React에서 사용되는 상태 관리 라이브러리.
컴포넌트의 상태 업데이트 관련 로직을 다른 파일로 분리시켜서 효율적으로 관리가능.


Redux용어

1) 액션(Action)

state에 무슨 동작을 할 것인지 적어놓는 객체.
액션은 type필드를 반드시 가지고 있어야함.

{
  type : 'ADD_TODO',
  data{
    id : 1,
    text : 'type 알아보기'
  }
}

2) 액션 생성함수(Action Creator)

Dispatch에 Action을 보낼때 사용하는 것으로 inline으로 Action을 넣는 것이 불편하기 때문에 action 객체를 return 해주는 함수를 만드는 것.

function addTodo(data) {
  return {
    type: 'ADD_TODO',
    data
  }
}

3) 디스패치(Dispatch)

Action Creater로 return 해준 Action을 parameter로 받아서 store의 reducer에게 넘겨는 역할.

const todoList = data => dispatch(addTodo(data))
todoList(data)

4) 리듀서(Reducer)

Dispatch를 통한 action의 type을 확인해 그에 맞는 동작하는 곳.

const init = {
  todos: []
}

function todoApp(state, action) {
  if (typeof state === 'undefined') {
    return init
  }

  return state
}

5) combineReducers

state에 여러 정보를 담고 싶을때 여러 reducer가 필요하게 되는데 그럴 때 사용하는 것.
2개의 reducer를 하나의 root reducer로 만들어주는 것.

const todoApp = combineReducers({
  user,
  todos
})

6) Store

Global State를 저장해놓는 저장소.
이 state는 엄격하게 관리해야 하기 때문에 dispatch라는 함수를 통해서만 접근이 가능.


Redux 실행 구조

https://kyun2da.dev/c98922b5a476e12b853576324f12f5c4/redux-data-flow.gif

profile
생각을 기록하자

0개의 댓글