-
Redux ToolkitProgramming/JavaScript & TypeScript 2022. 4. 1. 08:08728x90
이번에는 상태관리 라이브러리중에 하나인 ReduxToolkit에 대해서 알아보겠습니다.
Redux도 있지만, 최근에는 ReduxToolkit을 더 많이 사용하는 것 같습니다.
이유는 Redux의 단점을 보완해서 나온게 Redux Toolkit이기때문입니다.
Redux Toolkit | Redux Toolkit
The official, opinionated, batteries-included toolset for efficient Redux development
redux-toolkit.js.org
Redux는 라이브러리로써 React에서 많이 사용됩니다. Flux 패턴으로 구현되어 있으며 데이터를 단방향으로만 보내 데이
Redux 도입이전
React 컴포넌트 간에 Data를 전달하기 위해서는 props를 통해서만 가능했습니다.
컴포넌트가 많아졌을 때는 어떻게 될까요?
Right2에서 left2로 값을 전달하기 위해서는 Right1 -> Root -> Left1을 거쳐야됩니다.
Redux 도입 이후
Redux를 사용하면, 컴포넌트들이 사용할 수 있는 Store를 두는 것입니다.
Redux 예제
Redux에 대한 개념을 간단히(?) 이해했다면, 예제를 통해 더 이해해봅시다.
https://redux-toolkit.js.org/tutorials/quick-start 에 있는 소스를 분석해보면서 진행합니다.
index.js에서 Provider로 store를 넣어줍니다. 이렇게 하면 App 이하의 모든 component에서 store에 접근할 수 있도록 해줍니다.
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import App from './App' import { store } from './app/store' import { Provider } from 'react-redux' ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
CounterSlice.ts
클래스의 함수를 생각하면 쉬울것 같다..
reducer안에 값을 변경할 수 있는 메소드들을 넣는 것이다.
import { createSlice, PayloadAction } from '@reduxjs/toolkit' //interface 선언 export interface CounterState { value: number } //초기값 지정 const initialState: CounterState = { value: 0, } export const counterSlice = createSlice({ name: 'counter',//이름은 큰 상관없다 initialState, //초기값을 지정해주자 reducers: { //method같은 개념...어떤것을 할것인지 지정해주자 increment: (state) => { state.value += 1 }, decrement: (state) => { state.value -= 1 }, incrementByAmount: (state, action: PayloadAction<number>) => { state.value += action.payload }, }, }) //외부에서 쓸 수 있도록 선언 export const { increment, decrement, incrementByAmount } = counterSlice.actions export default counterSlice.reducer
store.ts
import { configureStore } from '@reduxjs/toolkit' import counterReducer from '../features/counter/counterSlice' //reducer를 넣어주고, 각 컴포넌트들이 사용할 수 있게 하자 export const store = configureStore({ reducer: { counter: counterReducer, }, }) // Infer the `RootState` and `AppDispatch` types from the store itself export type RootState = ReturnType<typeof store.getState> // Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState} export type AppDispatch = typeof store.dispatch
counter.ts
import React from 'react' import { RootState } from '../../app/store' import { useSelector, useDispatch } from 'react-redux' import { decrement, increment } from './counterSlice' export function Counter() { //counter.value가 바뀌면 count가 자동 업데이트 된다. const count = useSelector((state: RootState) => state.counter.value) const dispatch = useDispatch() return ( <div> <div> <button aria-label="Increment value" onClick={() => dispatch(increment())} //액션을 보내는 Disaptch > Increment </button> <span>{count}</span> //useSelector을 이용하여 값을 업데이트 받는다. <button aria-label="Decrement value" onClick={() => dispatch(decrement())} > Decrement </button> </div> </div> ) }
'Programming > JavaScript & TypeScript' 카테고리의 다른 글
[React 라이브러리] 라이브러리 기초 (0) 2022.05.09 Error 처리 (0) 2022.05.03 typescript class (0) 2022.02.20 typescript Interface (0) 2022.02.18 TypeScript Compiler(타입스크립트 컴파일러) (0) 2022.02.16