🌐 Web Development

Redux

Redux Toolkit

A predictable state management library for JavaScript apps. Unidirectional data flow and the immutability principle.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

Redux Toolkit Slice
// 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;
RTK Query API
// 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>
    );
}

πŸ—£οΈ Examples of Practical Conversations

πŸ’Ό State Management Selection Discussion
"Redux vs Zustand vs Jotai, which should we use?"

"If the project is large and tracking state with DevTools is important, Redux Toolkit is a good fit. For a small project or simple global state, Zustand is lighter. If most of your state is server state, TanStack Query alone may be enough. Redux is complex, but if the team is familiar with it, productivity is high."
πŸ” Code Review
"Isn't using state.items.push() in a Reducer an immutability violation?"

"Inside Redux Toolkit's createSlice, it's fine. Immer is built in, so even if you write it like a 'mutation', it internally returns a new object that maintains immutability. But when you write a reducer directly outside of a slice, you still have to preserve immutability."
πŸ“± Technical interview
"How do you handle asynchronous work in Redux?"

"Using RTK Query is the simplest. Otherwise, you create an async thunk with createAsyncThunk and handle the pending/fulfilled/rejected states in extraReducers. In the past, redux-saga and redux-observable were also widely used, but now RTK Query covers most cases."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

  • Excessive global state - Don't put all state in Redux. For local state such as form inputs or whether a modal is open, useState is enough. Keep only state that multiple components need to share in Redux.
  • Avoid Legacy Redux - Switch-statement reducers, action type constants, and createStore are outdated. Be sure to use Redux Toolkit's createSlice and configureStore.
  • Selector optimization - Selectors that return a new object/array every time cause unnecessary re-renders. Memoize with createSelector (reselect).

πŸ”— Related Terms

πŸ“š Learn More