ํฐ์คํ ๋ฆฌ ๋ทฐ
ํ์ ๊ณผ์ ๋ฅผ ๋ง์น๊ณ ๋์ ๊ณผ์ ์ธ RTK๋ฅผ ์งํํ์๋ค.

Context API๋ฅผ ์ฌ์ฉํ ๋ก์ง์์ RTK๋ก ๋ฐ๊พธ๋ ค๋ ํท๊ฐ๋ฆฌ๋ ๋ถ๋ถ์ด ๋ง์๋ค.
ํฌ๊ฒ RTK๋ฅผ ์ธํ ํ๋ ๋ฐฉ๋ฒ๊ณผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ผ๋ก ์ ๋ฆฌํด๋ณด๊ฒ ๋ค.
์ด๋ฒ ๊ธ์์๋ ์ธํ ํ๋ ๋ฐฉ๋ฒ!
RTK (Redux Toolkit) ๋?
๋ฆฌ๋์ค ํดํท์ ๋ฆฌ๋์ค๋ฅผ ๊ฐ๋ํ ๊ฒ
๋ฆฌ๋์ค๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด ์์ฑํ๋ ducks ํจํด์ ์์๋ค์ด ์ ์ฒด์ ์ธ ์ฝ๋์ ์์ ๋๋ฆฐ๋ค๋ ๊ฐ๋ฐ์๋ค์ ๋ถ๋ง์ด ๋ฐ์ํ๊ธฐ ์์ํ๊ณ ,
๋ฆฌ๋์ค ํ์์๋ ์ด๊ฒ์ ์์ฉํ์ฌ ์ฝ๋๋ ๋ ์ ๊ฒ, ๊ทธ๋ฆฌ๊ณ ๋ฆฌ๋์ค๋ฅผ ๋ ํธํ๊ฒ ์ฐ๊ธฐ ์ํ ๊ธฐ๋ฅ๋ค์ ํก์ํด์ ๋ง๋ ๊ฒ์ด ๋ฆฌ๋์คํดํท
๋ฆฌ๋์ค ํดํท์ ์ฐ๋ฆฌ๊ฐ ๋ฐฐ์ ๋ ๋ฆฌ๋์ค์ ๊ตฌ์กฐ๋ ํจ๋ฌ๋ค์์ด ๋ชจ๋ ๋๊ฐ๋ค.
์ฆ ์๋ก์ด ๊ฒ์ด ์๋๋ค.
๋ฆฌ๋์ค์ ์ ์ฒด ์ฝ๋์ ์์ ์ค์ด๊ธฐ ์ํด ์๋ก์ด API๊ฐ ์ถ๊ฐ๋์๊ณ ์ผ์ผํ ์์ผ๋ก ๋ง๋ค์ด ์ค์ผ ํ๋ ducks ํจํด์ ์์๋ค์ด ์ด๋์ ๋ ์๋ํ ๋์๋ค.
์ปดํฌ๋ํธ์์ useSelector๋ฅผ ํตํด์ ์ฌ์ฉํ๋ ๊ฒ์ ๋ชจ๋ ๋๊ฐ๋ค.
๋ฐ๋ ๋ถ๋ถ์ ๊ทธ์ ๋ชจ๋ ํ์ผ ๋ฟ์ด๋ค.
RTK Setting
์ ์ฒด์ ์ธ ์์๋ ์๋์ ๊ฐ๋ค.
1. ํจํค์ง ์ค์น ๋ฐ ํ์ผ ๊ตฌ์ฑ
2. ์คํ ์ด ์์ฑ (configureStore()
3. Slice ์์ฑ (createSlice() / reducer์ actions ์ ์)
4. ์ ์ํ reducer๋ฅผ store์ ์ ๋ ฅํ์ฌ store ๊ตฌ์ฑ
5. <Provider>๋ก ๊ฐ์ธ๊ธฐ, store ์ฃผ์
๐1. ํจํค์ง ์ค์น ๋ฐ ํ์ผ ๊ตฌ์ฑ
- ๋ฆฌ๋์ค ํดํท ์ค์น : yarn add @redux.js/toolkit
- RTK๋ moudules๋ฅผ ์ ์ ์ฐ๊ธฐ ๋๋ฌธ์
redux ํด๋ > silces ํด๋ > ~Slices.js

๐2. ์คํ ์ด ์์ฑ (configureStore() ์ฌ์ฉ)
- configureStore์ ๊ฐ์ฒด ํํ์ ์ธ์๋ฅผ 1๊ฐ ๊ฐ๋๋ค.
- ์ธ์์๋ ์ถํ slice์์ ์์ฑํ reducer๊ฐ ๋ค์ด์จ๋ค.
// ๊ฐ์ฒด ํํ์ ์ธ์ 1๊ฐ
export const store = configureStore({ ์ธ์ });
๐3. Slice ์์ฑ (createSlice() / reducer์ actions ์ ์)
- initalState ์ด๊ธฐ๊ฐ ๊ฐ์ ธ์ค๊ธฐ
// ๋ณดํต ๋ก์ง
const initialState = {
name: ""
};
// ๋ด๊ฐ ๊ตฌ์ฑํ ๋ก์ง
const initialState = [];
- createSlice() ์ฌ์ฉ
// ๋ณ์๋ action (type, value, creator), reducer๊ฐ ํฌํจ๋์ด์๋ค.
const *๋ณ์๋ช
= createSlice({ ๋ด๋ถ ๊ฐ์ฒด })
// ๋ด๋ถ ๊ฐ์ฒด
{ name: "์ด๋ฆ",
initialState,
reducers: {
ํจ์๋ช
1: (state, action) => {๋ฆฌ๋์ ๋ด์์ ์ค์ ์๋์ํฌ ๋ก์ง};
ํจ์๋ช
2: () => {};
};
};
- action creator
- ํจ์๋ช 1, ํจ์๋ช 2 ๊ฐ ๊ณง action creator
- action creator๋ฅผ ์คํํ๋ฉด action ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค.
- *๋ณ์๋ช ์ actions์์ ํจ์๋ฅผ ๋ฝ์์ ๋ด๋ณด๋ด๊ธฐ
export const { ํจ์๋ช
1, ํจ์๋ช
2 } = *๋ณ์๋ช
.actions;
- reducer
- ์ด์ ์ ์์ฑํ store์ ์ธ์๋ก ๋ค์ด๊ฐ
export default counterSlice.reducer;
๐4. ์ ์ํ reducer๋ฅผ store์ ์ ๋ ฅํ์ฌ store ๊ตฌ์ฑ
- store์ ์ธ์ ์๋ฆฌ์ reducer๋ฅผ ์ฃผ์
const store = configureStore ({ ๐๐ป๋ด๋ถ์ ๊ฐ์ฒด
reducer : { ๐๐ปkey ๋ด์ ๊ฐ์ฒด(reducer๋ค)
counter: counterSlice, ๐๐ปimport ์ ํ์ผ๋ช
ํ์ธ!
};
});
๐5. <Provider>๋ก ๊ฐ์ธ๊ธฐ, store ์ฃผ์
- APP.jsx (์ต์์ ํ์ผ)์์ <Provider>๋ก ๊ฐ์ธ๊ธฐ
- ๋ง๋ store ์ฃผ์ ํ๊ธฐ
// APP.jsx
const App = () => {
return (
<Provider store={store}>
<Router />
</Provider>
);
};
RTK ์ธํ ์ ์ํ ๋จ๊ณ๋ฅผ ์ ๋ฆฌํ๋ค.
๋ค์ ๊ธ์์๋ ์ค์ ์ ์ฉํ ๋ฐฉ๋ฒ์ ๋ฐํ์ผ๋ก RTK ์ฌ์ฉ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํ๊ฒ ๋ค.
'Language > React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ์ฌ๊ธฐ์ state๋ฅผ ๊ตณ์ด? - ์ฌ๋ฆผํฝ ์ ๋ ฌ(sort) (0) | 2025.02.11 |
|---|---|
| [Pokemon PJ_Day 4] RTK (2) - ์ฌ์ฉํ๊ธฐ (0) | 2025.02.06 |
| [โ๏ธ] Redux - counter ์ฑ ์์ฑ, redux ์ฌ์ดํด, dispatch (0) | 2025.02.03 |
| [โ๏ธ] Redux - ์๊ฐ ๋ฐ ์ค์ + counter ์ฑ ์ธํ (store ๋ง๋ค๊ธฐ) (0) | 2025.02.01 |
| [โ๏ธ] custom hook (0) | 2025.01.30 |