createSlice로 슬라이스 만들기
createSlice로 슬라이스를 정의하고 초기 상태와 리듀서 함수를 선언하며 자동 생성된 동작 생성자와 리듀서를 내보냅니다.
createSlice로 슬라이스 만들기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is a Redux Slice?
A slice is a self-contained piece of Redux logic for one feature of your app. It bundles the initial state, the reducer functions, and the auto-generated action creators together in a single file. The name comes from the idea that each slice represents a portion (slice) of the global Redux state tree.
Importing and Calling createSlice
createSlice is imported from @reduxjs/toolkit and accepts a configuration object with three required fields: name (a string prefix for action types), initialState (the starting value for this slice's state), and reducers (an object of reducer functions). It returns an object containing the slice reducer and the action creators.
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {},
});
export default counterSlice.reducer;Defining Reducer Functions
Each function you add to the reducers object becomes a case reducer that handles a specific action. RTK uses the Immer library under the hood, so you can write code that appears to mutate state directly — Immer converts it to an immutable update automatically. You never need to spread or copy the state object manually.
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment(state) {
state.value += 1; // Immer makes this safe
},
decrement(state) {
state.value -= 1;
},
incrementByAmount(state, action) {
state.value += action.payload;
},
},
});Auto-Generated Action Creators
createSlice automatically generates an action creator for each reducer function you define. You export them from the slice and call them when dispatching. The action creator name matches the reducer key, and the generated action type string follows the pattern sliceName/reducerName, for example counter/increment.
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
// Using in a component:
import { useAppDispatch } from '../../store/hooks';
import { increment } from './counterSlice';
const dispatch = useAppDispatch();
dispatch(increment()); // { type: 'counter/increment' }
dispatch(incrementByAmount(5)); // { type: 'counter/incrementByAmount', payload: 5 }Exporting the Reducer
The createSlice call returns an object with a reducer property. You export this as the default export and then import it in your store configuration. RTK composes all your slice reducers into the single root reducer automatically when you pass them to configureStore.
// counterSlice.ts
const counterSlice = createSlice({ /* ... */ });
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
// store/index.ts
import counterReducer from '../features/counter/counterSlice';
export const store = configureStore({
reducer: { counter: counterReducer },
});Defining TypeScript State Types
When using TypeScript, explicitly type your initialState so RTK can infer state and action types throughout the slice. Define an interface for your state and assign it as the type annotation on initialState. RTK will then infer the correct type for the state parameter in every reducer function automatically.
interface CounterState {
value: number;
status: 'idle' | 'loading' | 'failed';
}
const initialState: CounterState = {
value: 0,
status: 'idle',
};
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) {
state.value += 1; // TypeScript knows state is CounterState
},
},
});Using PayloadAction for Typed Payloads
When a reducer receives data from the dispatched action, import PayloadAction from RTK to type the action parameter. PayloadAction<number> tells TypeScript that action.payload must be a number. This prevents accidental mismatches between what the action creator accepts and what the reducer expects.
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
incrementByAmount(state, action: PayloadAction<number>) {
state.value += action.payload;
},
},
});The prepare Callback
The prepare callback lets you customize the action creator before RTK dispatches the action. You use it when you need to generate an ID, format data, or add a timestamp to the payload. The object returned by prepare must have a payload field, and optionally meta and error fields.
import { nanoid } from '@reduxjs/toolkit';
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: {
reducer(state, action: PayloadAction<{ id: string; text: string }>) {
state.push(action.payload);
},
prepare(text: string) {
return { payload: { id: nanoid(), text } };
},
},
},
});Resetting and Replacing State
Sometimes you need to reset a slice to its initial state — for example on user logout. You can return a completely new state value from a reducer instead of mutating. If you return a value, Immer uses it as the next state. This is the correct pattern for resetting or fully replacing state in a slice reducer.
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0, status: 'idle' },
reducers: {
reset() {
// Return the fresh initial value instead of mutating
return { value: 0, status: 'idle' };
},
},
});Responding to Actions from Other Slices
Slices can respond to actions defined in other slices using extraReducers. This avoids tight coupling — instead of importing one slice into another, you import only the action creator. Use the builder.addCase pattern to handle external action types inside your slice without adding them to the reducers key.
import { userSlice } from '../user/userSlice';
const cartSlice = createSlice({
name: 'cart',
initialState: { items: [] },
reducers: { /* own actions */ },
extraReducers: (builder) => {
builder.addCase(userSlice.actions.logout, (state) => {
state.items = []; // clear cart when user logs out
});
},
});Complete Counter Slice Example
Here is a complete, production-ready counter slice combining everything covered so far: a typed state interface, typed action creators with PayloadAction, and a reset action. Import this reducer into configureStore and its actions into components to have a fully working Redux feature.
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface CounterState { value: number; }
const initialState: CounterState = { value: 0 };
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; },
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload;
},
reset: () => initialState,
},
});
export const { increment, decrement, incrementByAmount, reset } = counterSlice.actions;
export default counterSlice.reducer;Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: createSlice bundles initial state, reducers, and action creators together, Immer lets you write mutating-style reducer code that stays immutable, and PayloadAction types the action payload for TypeScript safety. Next up we explore reading state with useSelector.
자주 묻는 질문
“createSlice로 슬라이스 만들기” 강의는 무료인가요?
네 — “createSlice로 슬라이스 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“createSlice로 슬라이스 만들기”에서 뭘 배우나요?
createSlice로 슬라이스를 정의하고 초기 상태와 리듀서 함수를 선언하며 자동 생성된 동작 생성자와 리듀서를 내보냅니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“createSlice로 슬라이스 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Redux 저장소와 Provider 설정
- createSlice로 슬라이스 만들기
- useSelector로 상태 읽기
- createAsyncThunk를 사용한 비동기 썽크