Action ➡️ Dispatch ➡️ Store ➡️ View
view(컴포넌트)에서
dispatch(store에서 주는 state를 바꾸는 함수)라는 함수를 통해 action(dispatch 함수 이름)이 발동되고,
reducer에 정의된 로직에 따라 store의 state가 변하고,
그 state를 쓰는 view(컴포넌트)가 변하게 된다.
state 는 루트 레벨에서 store 라는 곳에 저장되어 있고, 컴포넌트들은 이 store 를 구독하여, state 를 변경할 수 있는 함수를 전달받을 수 있게 된다.
이 함수들은 reducer 에서 정의하는데, 순수함수로 불변성을 지켜야 할 의무가 있다.
redux는 이전 state 의 참조값이 바뀌면 state가 바뀌었다고 인식하고 해당 state 를 사용하는 컴포넌트 모두에게 리랜더링을 요청하기 때문에, state 자체를 바꾸면 리랜더링이 안된다.
redux toolkit 은 이 불변성 유지를 내부적으로 알아서 작업해주는 아주 편리한 도구다!
Redux counter 예제 (redux toolkit)
Redux toolkit 참고 블로그
import { createSlice } from '@reduxjs/toolkit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export const incrementAsync = (amount) => (dispatch) => {
setTimeout(() => {
dispatch(incrementByAmount(amount))
}, 1000)
}
export const selectCount = (state) => state.counter.value
export default counterSlice.reducer
- 로컬에서 폴더명/파일명 폴더/파일 눌러서 임의로 바꿈(ex. temp)
- 원격 저장소 반영
- 다시 원하는 폴더/파일명으로 변경 후 원격 저장소 반영