Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 41 ยท Redux with React

Organizing Redux Code

Structure a Redux Toolkit app with feature folders, slice files, selectors, typed hooks and app-level setup. Learn the style guide rules that matter and avoid circular imports. Runnable examples included.

Redux does not care how you arrange files, but your team will. A good layout makes it obvious where a piece of logic lives, keeps related code together and lets the app grow without a tangle of imports. This lesson describes the layout the Redux maintainers recommend, plus the typed hooks and the handful of style rules that prevent most problems.

The file contents shown in plain code blocks need @reduxjs/toolkit and react-redux (read-only here). The runnable examples are small simulations of the structure in plain JavaScript, so you can see what the layout buys you.

Feature folders

Group code by feature (what the app does), not by type (all reducers here, all components there). The Redux style guide calls this the "feature folder" approach, with all logic for one feature in one place:

Text
src/
  app/
    store.js            // configureStore + RootState/AppDispatch types
    hooks.js            // typed useAppDispatch / useAppSelector
    rootReducer.js      // optional: only if you wrap or combine manually
  features/
    cart/
      cartSlice.js      // slice: state, reducers, actions, selectors
      cartSlice.test.js // reducer and selector tests
      Cart.jsx          // components that use the slice
      CartBadge.jsx
    auth/
      authSlice.js
      LoginForm.jsx
    todos/
      todosSlice.js
      TodoList.jsx
  components/           // shared, Redux-free UI (Button, Modal...)
  main.jsx

Why this works: to change the cart you open one folder; to delete a feature you delete one folder and one line in store.js; features can be moved or code-split together. A related idea is "ducks", the same thing described as a single file per feature that exports actions, reducer and selectors. A slice file is a duck.

Small apps can keep every slice in a flat slices/ folder. Pick feature folders as soon as features own components too.

What goes in a slice file

JavaScript
// features/cart/cartSlice.js (needs @reduxjs/toolkit; read-only here)
import { createSlice } from '@reduxjs/toolkit';

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: {} },
  reducers: {
    itemAdded(state, action) {
      const id = action.payload;
      state.items[id] = (state.items[id] ?? 0) + 1;
    },
    cleared(state) {
      state.items = {};
    },
  },
});

export const { itemAdded, cleared } = cartSlice.actions;     // 1. actions
export const selectCartCount = (state) =>                    // 2. selectors
  Object.values(state.cart.items).reduce((a, b) => a + b, 0);
export default cartSlice.reducer;                            // 3. reducer

Everything outside the folder imports from this one file. Nobody else needs to know that the state is { items: { [id]: qty } }; they use selectCartCount.

The store file

JavaScript
// app/store.js
import { configureStore } from '@reduxjs/toolkit';
import cartReducer from '../features/cart/cartSlice';
import authReducer from '../features/auth/authSlice';

export const store = configureStore({
  reducer: {
    cart: cartReducer,
    auth: authReducer,
  },
});

Adding a feature means adding one import and one line here. The next example simulates that: each "file" is an object, and the store is assembled from whatever features are registered.

JS Adding a feature is one line in the store

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Selectors hide the state shape

Components should read state through selector functions, not by reaching into state.cart.items[...]. Then, when you change the shape (maybe to normalise it), you edit one selector instead of fifty components.

JS Changing the state shape without touching components

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Typed hooks (TypeScript)

In a TypeScript project, export the types from the store and create pre-typed hooks once, so components get autocomplete for state and dispatch. React-Redux 9 provides .withTypes:

TypeScript
// app/store.ts (read-only)
export const store = configureStore({ reducer: { cart: cartReducer } });
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// app/hooks.ts
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();

Components then import useAppDispatch and useAppSelector instead of the plain hooks. In JavaScript projects you do not need this file, though some teams keep it anyway as a single place to wrap the hooks later.

Style guide rules worth memorising

The official Redux style guide has many rules. These are the ones that prevent real bugs:

  1. Do not mutate state outside of Immer reducers; no side effects in reducers.
  2. Do not put non-serializable values in state or actions.
  3. Only one Redux store per app.
  4. Use Redux Toolkit, createSlice and configureStore.
  5. Use Immer for updates, organise by feature, put as much logic as possible in reducers rather than in components.
  6. Name action types domain/eventName; model events, not setters.
  7. Write meaningful action type names and use selector functions to read state.
  8. Normalise complex state and keep state minimal, deriving the rest.
  9. Use the React-Redux hooks API and call useSelector many times with narrow selectors.

You have now met most of these in action. The rest of the course applies them to async logic, middleware, testing and projects.

Avoiding circular imports

A frequent trap in larger apps: authSlice imports an action from cartSlice and cartSlice imports one from authSlice. JavaScript modules can then load in the wrong order and an action creator is undefined when extraReducers runs. Rules of thumb:

  • A slice may import actions from other slices only in one direction.
  • Put shared actions (app/reset, auth/loggedOut) in their own file created with createAction, and import that file from both (createAction).
  • Do not import the store into slice files. If a thunk needs it, use the thunkAPI argument (getState, dispatch) provided by Toolkit.
  • Components may import from any slice; slices must not import components.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the recommended way to group Redux code in a larger app?

    Feature folders keep everything about one feature together, so features are easy to change, move or delete.
  2. 2. Why should components use selector functions instead of reading state.cart.items directly?

    Selectors decouple components from the exact shape of the store.
  3. 3. What does useDispatch.withTypes<AppDispatch>() give you?

    It creates a typed hook once, so components get correct typings without annotating each use.
  4. 4. How do you avoid circular imports between two slices that both need the same action?

    A neutral shared file breaks the cycle: both slices import it, and it imports neither.

Summary

  • Organise by feature: one folder per feature with its slice and components; a slice file exports actions, selectors and the reducer.
  • app/store.js is the only file that knows every slice; adding a feature is a one-line change.
  • Read state through selectors so the state shape can change safely.
  • In TypeScript, export RootState and AppDispatch and create typed hooks with .withTypes.
  • Follow the core style rules and avoid circular imports with shared createAction files.

Next: Connect and Legacy Redux