Redux/Basic

Redux - createStore

고코모옹 2021. 12. 31. 13:00

createStore(reducer, [preloadedState], [enhancer])

  • 저장소(store) 생성
  • App에는 하나의 저장소(store)만 있어야 한다.

 

Arguments

  1. reducer (Function): 현재 상태 트리와 수행할 액션이 주어지면, 다음 상태 트리를 반환해주는 함수
  2. [preloadedState] (any)
    • 초기 상태
    • 선택적으로 범용적인 앱의 서버에서 상태를 수화하거나 이전에 직렬화된 사용자 세션을 복원하도록 지정할 수 있다.
    • combineReducers로 reducer를 생성한 경우, 전달된 key와 동일한 형태의 일반 객체여야만 한다.

  1. [enhancer] (Function)
    • 미들웨어, 시간 여행, 지속성 등과 같은 third-party 기능으로 저장소를 향상시키기 위해 선택적으로 지정할 수 있다.
    • Redux와 함께 제공되는 유일한 저장소 enhancer는 applyMiddleware() 이다.

 

Returns

(Store): App의 전체 상태를 보유하는 객체이다. 상태를 변경하는 유일한 방법은 액션(Action)을 전달(dispatch)하는 것이다.
                상태 변경 사항을 구독하여 UI를 업데이트 할 수도 있다.

 

 

Example

import { createStore } from 'redux'

function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([action.text])
    default:
      return state
  }
}

const store = createStore(todos, ['Use Redux'])

store.dispatch({
  type: 'ADD_TODO',
  text: 'Read the docs'
})

console.log(store.getState())
// [ 'Use Redux', 'Read the docs' ]

 

Store Console


[ 참고자료 ]

https://redux.js.org/api/createstore