Redux
Redux Toolkit
A predictable state management library for JavaScript apps. Unidirectional data flow and the immutability principle.
Redux Toolkit
A predictable state management library for JavaScript apps. Unidirectional data flow and the immutability principle.
Redux is a JavaScript state management library developed by Dan Abramov in 2015, and is a simplified implementation of the Flux architecture. It has three core principles. Single Source of Truth - the entire app state is stored in a single Store. State is Read-Only - it can only be changed through Actions. Pure Functions - a Reducer is a pure function that takes the previous state and an Action and returns a new state.
Redux's data flow is unidirectional. When a user event occurs, dispatch(action) is called, the Store runs the Reducer to compute a new state, and the subscribed components re-render. This predictable flow makes debugging easier and makes it possible to track state changes. Redux DevTools enables Time Travel Debugging.
Redux Toolkit (RTK) is a modern implementation of Redux officially released in 2019, which greatly reduced boilerplate. createSlice defines Actions and a Reducer at once, and Immer is built in to handle immutability automatically. configureStore automates the DevTools and middleware setup. RTK is now the standard way to use Redux.
RTK Query is a data fetching library added in Redux Toolkit 1.6, providing caching, automatic refetching, and optimistic updates similar to React Query. When you define endpoints with createApi, hooks (such as useGetUsersQuery and useCreateUserMutation) are generated automatically. It is no longer necessary to combine Redux with a separate library for server state management.
// features/cart/cartSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartState {
items: CartItem[];
isOpen: boolean;
}
const initialState: CartState = {
items: [],
isOpen: false,
};
const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
// Immerλ‘ "λ³κ²½"μ²λΌ μμ±ν΄λ λΆλ³μ± μλ μ²λ¦¬
addItem: (state, action: PayloadAction<Omit<CartItem, 'quantity'>>) => {
const existingItem = state.items.find(item => item.id === action.payload.id);
if (existingItem) {
existingItem.quantity += 1;
} else {
state.items.push({ ...action.payload, quantity: 1 });
}
},
removeItem: (state, action: PayloadAction<string>) => {
state.items = state.items.filter(item => item.id !== action.payload);
},
updateQuantity: (state, action: PayloadAction<{ id: string; quantity: number }>) => {
const item = state.items.find(item => item.id === action.payload.id);
if (item) {
item.quantity = action.payload.quantity;
}
},
clearCart: (state) => {
state.items = [];
},
toggleCart: (state) => {
state.isOpen = !state.isOpen;
},
},
});
// Action creators μλ μμ±
export const { addItem, removeItem, updateQuantity, clearCart, toggleCart } = cartSlice.actions;
// Selectors
export const selectCartItems = (state: RootState) => state.cart.items;
export const selectCartTotal = (state: RootState) =>
state.cart.items.reduce((total, item) => total + item.price * item.quantity, 0);
export const selectCartCount = (state: RootState) =>
state.cart.items.reduce((count, item) => count + item.quantity, 0);
export default cartSlice.reducer;
// services/api.ts - RTK Query
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
interface User {
id: number;
name: string;
email: string;
}
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: '/api',
prepareHeaders: (headers) => {
const token = localStorage.getItem('token');
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return headers;
},
}),
tagTypes: ['User', 'Post'],
endpoints: (builder) => ({
// Query - GET μμ²
getUsers: builder.query<User[], void>({
query: () => '/users',
providesTags: ['User'],
}),
getUser: builder.query<User, number>({
query: (id) => `/users/${id}`,
providesTags: (result, error, id) => [{ type: 'User', id }],
}),
// Mutation - POST/PUT/DELETE μμ²
createUser: builder.mutation<User, Omit<User, 'id'>>({
query: (body) => ({
url: '/users',
method: 'POST',
body,
}),
invalidatesTags: ['User'], // λͺ©λ‘ μλ 리νμΉ
}),
updateUser: builder.mutation<User, Partial<User> & Pick<User, 'id'>>({
query: ({ id, ...body }) => ({
url: `/users/${id}`,
method: 'PATCH',
body,
}),
invalidatesTags: (result, error, { id }) => [{ type: 'User', id }],
}),
deleteUser: builder.mutation<void, number>({
query: (id) => ({
url: `/users/${id}`,
method: 'DELETE',
}),
invalidatesTags: ['User'],
}),
}),
});
// Hooks μλ μμ±
export const {
useGetUsersQuery,
useGetUserQuery,
useCreateUserMutation,
useUpdateUserMutation,
useDeleteUserMutation,
} = api;
// -------------------------------------------------
// μ»΄ν¬λνΈμμ μ¬μ©
function UserList() {
const { data: users, isLoading, error } = useGetUsersQuery();
const [deleteUser, { isLoading: isDeleting }] = useDeleteUserMutation();
if (isLoading) return <div>λ‘λ© μ€...</div>;
if (error) return <div>μλ¬ λ°μ</div>;
return (
<ul>
{users?.map(user => (
<li key={user.id}>
{user.name}
<button
onClick={() => deleteUser(user.id)}
disabled={isDeleting}
>
μμ
</button>
</li>
))}
</ul>
);
}
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free