티스토리 뷰

리덕스 (Redux)

Store => createStore

import { createStore } from 'redux'

Reducer

리듀서 함수를 선언하고 그 함수를 넘겨서 store를 생성하면 된다.

export const todosReducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return state.concat({
        id: action.payload.id,
        text: action.payload.text,
        completed: false
      })
    case TODO_TOGGLED:
      return state.map(todo => {
        if (todo.id !== action.payload.id) return todo

        return {
          ...todo,
          completed: !todo.completed
        }
      })
    default:
      return state
  }
}
const store = createStore(todosReducer)

Actions

액션 함수를 별개로 선언하고 dispatch에 액션 함수를 호출해서 넘겨준다.

const ADD_TODO = 'ADD_TODO'
const TODO_TOGGLED = 'TODO_TOGGLED'

export const addTodo = (text, id) => ({
  type: ADD_TODO,
  payload: { text, id }
})

export const todoToggled = id => ({
  type: TODO_TOGGLED,
  payload: id
})
dispatch(addTodo(inputValue));

 

 

리덕스 툴킷 (Redux Toolkit)

Store => configureStore

import { configureStore } from '@reduxjs/toolkit'

Reducer + Action => Slice

createSlice의 인자에 초기값과, 리듀서가 되는 객체를 넣어준다. reducers의 값으로 state를 변경하는 함수들을 선언한다. 첫 번째 인자로는 state를 받는다. 컴포넌트에서 액션을 사용할 수 있도록 액션도 export 하고, 스토어에 넣어줘야 하기 때문에 default는 slice.reducer로 해준다.

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 default counterSlice.reducer

그리고 default로 export한 slice.reducer를 store에 reducer에 값으로 위에서 선언한 슬라이스의 리듀서를 넣어주면 된다.

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'

export default configureStore({
  reducer: {
    counter: counterReducer
  }
})

 

그래서 store.reducer.등록한 슬라이스.reducer의 value를 useSelector로 접근하게 된다.

useSelector( configure.reducer => configure.reducer.설정한 슬라이스 이름.value )가 된다! configure.reducer == state

const count = useSelector(state => state.counter.value)

그리고 설정한 액션 이름을 import하고 dispatch에게 넘겨주면 된다.

dispatch(설정한 액션 이름())

onClick={() => dispatch(increment())}

호출할 때는 dispatch에 함수를 호출해서 넘겨주는 형태지만 사용하기까지 보일러 플레이트 코드의 양이 달라진다.

redux는 초기값, 액션 타입 문자열, 액션 함수, 리듀서, 스토어를 따로 작성해줘야 하지만

redux-toolkit은 리듀서와 스토어만 따로 작성해 주면 된다.

확실히 줄어들어서 리덕스 측에서도 리덕스 툴킷 사용을 권유하는 것 같다!

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함