> For the complete documentation index, see [llms.txt](https://optim-finance.gitbook.io/optim-finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://optim-finance.gitbook.io/optim-finance/oada-ui/tutorials/state-management-and-data-flow.md).

# State Management and Data Flow

This tutorial covers how state management is implemented in the project using Redux Toolkit.

### Overview

The project uses Redux Toolkit for state management, with a focus on:

* Wallet state management
* Alert/notification system
* Type-safe state access
* Service injection for async operations

### Store Structure

The Redux store is organized as follows:

```
src/store/
├── index.ts           # Store configuration and setup
├── hooks.ts           # Custom hooks for Redux
├── wallet.ts          # Wallet-related utilities
└── slices/            # Redux slices
    ├── walletSlice.ts # Wallet state management
    └── alertSlice.ts  # Alert/notification system
```

### Store Configuration

The main store configuration is in `src/store/index.ts`:

```typescript
// Store configuration with service injection
export const store = configureStore({
  reducer: {
    wallet: walletReducer,
    oadaActions: oadaActionsReducer,
    alert: alertReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      thunk: {
        extraArgument: services,
      },
    }),
});
```

Key features:

* Service injection for async operations
* Combined reducers for different features
* Type-safe store configuration

### Slices

#### Wallet Slice (`walletSlice.ts`)

Manages all wallet-related state:

* Wallet connection status
* UTxO tracking
* Balance calculations
* WebSocket notifications
* Reward account management

Example usage:

```typescript
const walletState = useSelector((state: RootState) => state.wallet);
```

#### Alert Slice (`alertSlice.ts`)

Handles application alerts and notifications:

* Alert display
* Alert removal
* Unique ID generation
* Type-safe alert management

Example usage:

```typescript
const dispatch = useDispatch();
dispatch(setAlert({ type: "success", message: "Operation successful" }));
```

### Custom Hooks

The project provides custom hooks in `src/store/hooks.ts` for common Redux operations:

* `useAppDispatch`: Typed dispatch function
* `useAppSelector`: Typed selector hook
* Wallet-specific hooks
* Alert management hooks

Example:

```typescript
import { useAppDispatch, useAppSelector } from "../store/hooks";

function MyComponent() {
  const dispatch = useAppDispatch();
  const wallet = useAppSelector((state) => state.wallet);

  // Use wallet state and dispatch actions
}
```

### Best Practices

1. **State Access**
   * Use custom hooks for type-safe state access
   * Keep selectors close to where they're used
   * Memoize complex selectors
2. **Actions**
   * Use Redux Toolkit's `createAsyncThunk` for async operations
   * Keep actions focused and specific
   * Use proper typing for payloads
3. **Reducers**
   * Keep reducers pure
   * Use Immer for immutable updates
   * Handle all possible action types
4. **Middleware**
   * Use middleware for side effects
   * Keep middleware focused and specific
   * Use proper typing for middleware

### Type Safety

The project maintains type safety through:

* Properly typed store configuration
* Type-safe actions and reducers
* Typed selectors and hooks
* Service injection typing

Example of type-safe action:

```typescript
const setAlert = createAction<AlertPayload>("alert/set");
```

### Testing

When testing Redux code:

1. Test reducers in isolation
2. Test action creators
3. Test selectors
4. Test async thunks with mocked services

Example test:

```typescript
describe("walletSlice", () => {
  it("should handle initial state", () => {
    expect(walletReducer(undefined, { type: "unknown" })).toEqual({
      // Expected initial state
    });
  });
});
```

### Next Steps

Now that you understand state management and data flow, you can proceed to:

1. Authentication and Authorization
2. API Integration and Services

### Additional Resources

* [Redux Toolkit Documentation](https://redux-toolkit.js.org/)
* [React Query Documentation](https://react-query.tanstack.com/)
* [React Context Documentation](https://reactjs.org/docs/context.html)
* [Redux Best Practices](https://redux.js.org/style-guide/style-guide)
