Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+348 -151
View File
@@ -1,196 +1,393 @@
---
description: This rule provides comprehensive guidance on Redux best practices, covering code structure, performance optimization, testing strategies, and common pitfalls to ensure robust and maintainable Redux applications.
globs: *.js,*.jsx,*.ts,*.tsx
description: This guide defines the definitive best practices for using Redux in our projects, mandating Redux Toolkit (RTK) for all state management logic to ensure consistency, maintainability, and optimal performance.
globs: **/*.{js,jsx}
---
- **Introduction:** This document outlines best practices for developing applications with Redux, covering various aspects from code organization to performance optimization.
# redux Best Practices
## 1. Code Organization and Structure:
Redux is our standard for predictable state management. **All new Redux code MUST use Redux Toolkit (RTK)**. RTK simplifies Redux, enforces best practices, and eliminates boilerplate. Do not use vanilla Redux APIs directly.
- **Directory Structure:** Organize your Redux-related files in a clear and maintainable structure. A feature-based approach is recommended.
- Example:
src/
├── app/
│ ├── store.js # Redux store configuration
├── features/
│ ├── counter/ # Feature module (e.g., 'counter')
│ │ ├── counterSlice.js # Redux slice (reducers + actions)
│ │ ├── Counter.jsx # React component
│ │ ├── counterAPI.js # API interaction logic
│ │ └── counterSelectors.js # Selectors
│ ├── todos/
│ │ └── ...
├── components/ # Reusable UI components
├── utils/ # Utility functions
└── ...
## 1. Code Organization and Structure
- **File Naming Conventions:** Use consistent and descriptive names for your files.
- Example:
- `counterSlice.js` for Redux slice files
- `Counter.jsx` for React components
- `counterActions.js` or preferably included in slice
- `counterSelectors.js` for selectors
Organize your Redux logic by feature, using a "slice" approach. This co-locates all related state, actions, and reducers, improving discoverability and maintainability.
- **Module Organization:** Group related logic into modules. Each feature should have its own directory containing its Redux slice, components, and selectors.
### 1.1. Feature-First Directory Structure
- **Component Architecture:** Use a container/presentational component pattern to separate data fetching and state management logic from UI rendering.
- **Container Components:** Connect to the Redux store and pass data to presentational components.
- **Presentational Components:** Focus on UI rendering and receive data and callbacks as props.
Group all Redux-related files for a specific feature within a single directory.
- **Code Splitting Strategies:** Implement code splitting to reduce the initial bundle size and improve loading times.
- **Route-based splitting:** Load different parts of the application based on the current route.
- **Component-based splitting:** Lazy-load components that are not immediately needed.
- Use `React.lazy` and `<Suspense>` for component-based splitting.
```
src/
├── app/
│ ├── store.js // Root store configuration
│ └── hooks.js // Pre-typed Redux hooks (for TS)
└── features/
├── users/
│ ├── usersSlice.js // User slice (reducer, actions)
│ └── UserList.jsx // Component using user slice
└── posts/
├── postsSlice.js // Post slice
└── PostEditor.jsx // Component using post slice
```
## 2. Common Patterns and Anti-patterns:
### 1.2. Single-File Slices
- **Design Patterns:**
- **Flux Standard Actions (FSA):** A convention for structuring Redux actions with a `type` and an optional `payload` and `error` property.
- **Selectors:** Use selectors (e.g., with Reselect) to derive data from the Redux store efficiently.
- **Thunks/Sagas:** Manage asynchronous side effects using Redux Thunk or Redux Saga.
Define your reducer, initial state, and action creators in a single file using `createSlice`. This is the "ducks" pattern, simplified by RTK.
- **Recommended Approaches:**
- **Redux Toolkit:** Use Redux Toolkit to simplify Redux development and reduce boilerplate.
- **Immutability:** Treat state as immutable and use immutable data structures or techniques to update it.
- **Normalization:** Normalize your state to reduce data duplication and improve data consistency.
❌ **BAD: Scattered Redux files**
```javascript
// src/features/posts/actions.js
export const addPost = (payload) => ({ type: 'posts/addPost', payload });
- **Anti-patterns and Code Smells:**
- **Mutating State Directly:** Never mutate state directly. Always create new copies of objects and arrays.
- **Putting too much logic in components:** Keep components focused on rendering. Move complex logic to reducers, selectors, or middleware.
- **Large Reducers:** Split large reducers into smaller, more manageable reducers using `combineReducers`.
- **Over-fetching Data:** Fetch only the data that is needed by the component. Use selectors to derive specific data subsets from the state.
// src/features/posts/reducers.js
const postsReducer = (state = [], action) => { /* ... */ };
- **State Management Best Practices:**
- **Single Source of Truth:** Keep all application state in the Redux store.
- **Predictable State Updates:** Ensure that state updates are predictable and deterministic.
- **Minimize Global State:** Only store data that is truly global in the Redux store. Local component state should be used for UI-specific data.
// src/features/posts/constants.js
const ADD_POST = 'posts/addPost';
```
- **Error Handling Patterns:**
- **Action-based Error Handling:** Dispatch actions to indicate errors and update the state accordingly.
- **Middleware Error Handling:** Use middleware to catch errors and log them to a central error reporting service.
✅ **GOOD: Co-located slice with `createSlice`**
```javascript
// src/features/posts/postsSlice.js
import { createSlice, nanoid } from '@reduxjs/toolkit';
## 3. Performance Considerations:
const postsSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
postAdded: {
reducer(state, action) {
state.push(action.payload);
},
prepare(title, content, userId) {
return {
payload: {
id: nanoid(),
title,
content,
user: userId,
date: new Date().toISOString(),
},
};
},
},
// ... other reducers
},
});
- **Optimization Techniques:**
- **Memoization:** Use memoization to avoid unnecessary re-renders. Use `React.memo` for functional components and `shouldComponentUpdate` for class components.
- **Selectors:** Use selectors with memoization (e.g., Reselect) to avoid recomputing derived data when the input state hasn't changed.
- **Batch Updates:** Batch multiple state updates into a single update to reduce the number of re-renders.
- **Debouncing/Throttling:** Use debouncing or throttling to limit the frequency of updates.
export const { postAdded } = postsSlice.actions;
export default postsSlice.reducer;
```
- **Memory Management:**
- **Avoid Memory Leaks:** Clean up event listeners and timers when components unmount.
- **Optimize Data Structures:** Use efficient data structures to reduce memory usage.
### 1.3. Root Store Configuration
- **Rendering Optimization:**
- **Virtualization:** Use virtualization for large lists to only render the visible items.
- **Code Splitting:** Reduce the initial bundle size by splitting the code into smaller chunks.
Centralize your store setup in `src/app/store.js` using `configureStore`. This automatically includes `redux-thunk`, Redux DevTools integration, and development-time checks for common mistakes.
- **Bundle Size Optimization:**
- **Tree Shaking:** Remove unused code from the bundle using tree shaking.
- **Minification:** Minify the code to reduce the bundle size.
- **Compression:** Compress the bundle using Gzip or Brotli.
```javascript
// src/app/store.js
import { configureStore } from '@reduxjs/toolkit';
import usersReducer from '../features/users/usersSlice';
import postsReducer from '../features/posts/postsSlice';
- **Lazy Loading Strategies:**
- **Route-based Lazy Loading:** Load different routes on demand.
- **Component-based Lazy Loading:** Load components on demand using `React.lazy`.
export const store = configureStore({
reducer: {
users: usersReducer,
posts: postsReducer,
},
// middleware and devTools are configured by default
});
```
## 4. Security Best Practices:
## 2. State Organization
- **Common Vulnerabilities:**
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user inputs and escaping outputs.
- **Cross-Site Request Forgery (CSRF):** Protect against CSRF attacks by using anti-CSRF tokens.
- **Data Injection:** Prevent data injection attacks by validating and sanitizing inputs.
Keep your state as flat and normalized as possible, especially for collections of items.
- **Input Validation:**
- **Client-Side Validation:** Validate inputs on the client-side to provide immediate feedback to the user.
- **Server-Side Validation:** Validate inputs on the server-side to ensure data integrity.
### 2.1. Normalize Data for Collections
- **Authentication and Authorization Patterns:**
- **JWT (JSON Web Tokens):** Use JWTs for authentication and authorization.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to different parts of the application.
Store collections of items (e.g., users, posts) in a normalized way: an object mapping IDs to item objects, plus an array of IDs. This prevents data duplication and simplifies updates.
- **Data Protection Strategies:**
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data to protect it from unauthorized access.
❌ **BAD: Array of objects (hard to update)**
```javascript
// state.posts = [{ id: '1', title: 'A', author: { id: 'u1', name: 'Alice' } }, ...]
// Updating Alice's name requires iterating through all posts.
```
- **Secure API Communication:**
- **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
- **API Rate Limiting:** Implement API rate limiting to prevent abuse.
✅ **GOOD: Normalized state (easy to update)**
```javascript
// state.posts = {
// ids: ['1', '2'],
// entities: {
// '1': { id: '1', title: 'A', authorId: 'u1' },
// '2': { id: '2', title: 'B', authorId: 'u2' },
// },
// };
// state.users = {
// ids: ['u1', 'u2'],
// entities: {
// 'u1': { id: 'u1', name: 'Alice' },
// 'u2': { id: 'u2', name: 'Bob' },
// },
// };
// Updating Alice's name is a single direct lookup: state.users.entities['u1'].name = 'Alicia'
```
Use RTK's `createEntityAdapter` to simplify managing normalized state.
## 5. Testing Approaches:
## 3. Side Effects
- **Unit Testing Strategies:**
- **Test Reducers:** Test reducers to ensure that they update the state correctly.
- **Test Actions:** Test actions to ensure that they dispatch the correct payloads.
- **Test Selectors:** Test selectors to ensure that they derive the correct data from the state.
Handle all side effects (async logic, API calls) outside of reducers.
- **Integration Testing:**
- **Test Components:** Test components to ensure that they render correctly and interact with the Redux store.
- **Test Middleware:** Test middleware to ensure that they handle side effects correctly.
### 3.1. Use RTK Query for Data Fetching
- **End-to-end Testing:**
- **Test User Flows:** Test user flows to ensure that the application works as expected from the user's perspective.
**RTK Query is the preferred solution for data fetching and caching.** It drastically reduces boilerplate for API interactions.
- **Test Organization:**
- **Test Directory Structure:** Organize tests in a clear and maintainable structure.
- Example:
src/
├── features/
│ ├── counter/
│ │ ├── counterSlice.test.js
│ │ ├── Counter.test.jsx
❌ **BAD: Manual `createAsyncThunk` for every API call**
```javascript
// src/features/posts/postsSlice.js
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
- **Mocking and Stubbing:**
- **Mock API Calls:** Mock API calls to isolate components and reducers during testing.
- **Stub Dependencies:** Stub external dependencies to control their behavior during testing.
export const fetchPosts = createAsyncThunk('posts/fetchPosts', async () => {
const response = await axios.get('/api/posts');
return response.data;
});
// ... then manually handle loading states, errors, caching
```
## 6. Common Pitfalls and Gotchas:
✅ **GOOD: RTK Query for data fetching**
```javascript
// src/services/postsApi.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
- **Frequent Mistakes:**
- **Forgetting to Return State:** Reducers must always return the new state. If no change, return the original state.
- **Incorrectly Updating Nested Objects:** Remember to create copies of all levels when updating nested objects.
- **Not Handling Asynchronous Actions Correctly:** Using thunks or sagas incorrectly can lead to unexpected behavior.
export const postsApi = createApi({
reducerPath: 'postsApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),
endpoints: (builder) => ({
getPosts: builder.query({
query: () => 'posts',
}),
addPost: builder.mutation({
query: (newPost) => ({
url: 'posts',
method: 'POST',
body: newPost,
}),
}),
}),
});
- **Edge Cases:**
- **Initial State:** Ensure that the initial state is correctly defined.
- **Handling Errors:** Handle errors gracefully and provide informative error messages.
- **Empty States:** Handle empty states correctly to avoid unexpected behavior.
export const { useGetPostsQuery, useAddPostMutation } = postsApi;
// Automatically handles loading, error, caching, re-fetching.
```
- **Version-Specific Issues:**
- **React Redux v8 vs v7:** Be aware of the changes introduced in React Redux v8, such as the improved performance and the new `useSyncExternalStore` hook.
### 3.2. Use `createAsyncThunk` for Complex Async Logic
- **Compatibility Concerns:**
- **Browser Compatibility:** Ensure that the application works correctly in all supported browsers.
- **Device Compatibility:** Ensure that the application works correctly on all supported devices.
For async logic that isn't simple data fetching (e.g., complex multi-step processes, interacting with non-API services), use `createAsyncThunk`.
- **Debugging Strategies:**
- **Redux DevTools:** Use the Redux DevTools extension to inspect the state and track actions.
- **Console Logging:** Use console logging to debug code and track state changes.
- **Debugging Tools:** Use browser debugging tools to step through code and inspect variables.
```javascript
// src/features/notifications/notificationsSlice.js
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
## 7. Tooling and Environment:
export const markAllNotificationsRead = createAsyncThunk(
'notifications/markAllRead',
async (_, { getState }) => {
const { notifications } = getState();
// Simulate complex logic, e.g., batch update in DB
await someExternalService.updateMany(notifications.map(n => n.id));
return notifications.map(n => n.id);
}
);
```
- **Recommended Development Tools:**
- **Redux DevTools Extension:** Inspect Redux state and actions.
- **VS Code with Redux Extension:** Provides code completion, linting, and debugging support for Redux.
## 4. Common Pitfalls and Gotchas
- **Build Configuration:**
- **Webpack/Parcel/Rollup:** Use a module bundler to bundle the code and optimize it for production.
- **Babel:** Use Babel to transpile the code to older versions of JavaScript.
Avoid these common mistakes to prevent bugs and ensure predictable state.
- **Linting and Formatting:**
- **ESLint:** Use ESLint to enforce code style and prevent errors.
- **Prettier:** Use Prettier to automatically format the code.
### 4.1. Never Mutate State Outside of Reducers (or Immer)
- **Deployment Best Practices:**
- **Environment Variables:** Use environment variables to configure the application for different environments.
- **CDN:** Use a CDN to serve static assets.
Directly modifying the Redux state is the #1 cause of bugs. `createSlice` uses Immer, allowing "mutative" syntax safely within reducers.
- **CI/CD Integration:**
- **Automated Testing:** Run tests automatically as part of the CI/CD pipeline.
- **Automated Deployment:** Deploy the application automatically to different environments.
❌ **BAD: Mutating state directly**
```javascript
// In a component or thunk
dispatch(someAction());
store.getState().posts[0].title = 'New Title'; // 🚨 DANGER!
```
This comprehensive guide should help you build robust, maintainable, and performant Redux applications. Remember to stay up-to-date with the latest best practices and tools in the Redux ecosystem.
❌ **BAD: Mutating state in a vanilla reducer**
```javascript
// In a reducer without Immer
const postsReducer = (state = [], action) => {
if (action.type === 'posts/update') {
state[0].title = action.payload.title; // 🚨 DANGER!
return state; // Returns mutated state
}
return state;
};
```
✅ **GOOD: Safe immutable updates with `createSlice` (Immer)**
```javascript
// In a createSlice reducer
const postsSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
postUpdated(state, action) {
const { id, title } = action.payload;
const existingPost = state.find(post => post.id === id);
if (existingPost) {
existingPost.title = title; // ✅ Safe with Immer!
}
},
},
});
```
### 4.2. Reducers Must Be Pure
Reducers must be pure functions: given the same inputs (state, action), they must always produce the same output, without side effects.
❌ **BAD: Reducer with side effects**
```javascript
const postsReducer = (state = [], action) => {
if (action.type === 'posts/add') {
console.log('Adding post!'); // 🚨 Side effect
return [...state, { ...action.payload, timestamp: Date.now() }]; // 🚨 Non-deterministic
}
return state;
};
```
✅ **GOOD: Pure reducer**
```javascript
const postsSlice = createSlice({
name: 'posts',
initialState: [],
reducers: {
postAdded: {
reducer(state, action) {
state.push(action.payload);
},
prepare(title, content) {
return {
payload: {
id: nanoid(),
title,
content,
date: new Date().toISOString(), // ✅ Deterministic if called in prepare
},
};
},
},
},
});
```
### 4.3. Avoid Non-Serializable Values in State or Actions
Do not store Promises, Symbols, Maps/Sets, functions, or class instances in your Redux state or dispatched actions. This breaks DevTools and state rehydration.
❌ **BAD: Non-serializable value in state**
```javascript
// state.user = { id: '1', name: 'Alice', promise: somePromise() } // 🚨 DANGER!
```
✅ **GOOD: Serializable values only**
```javascript
// state.user = { id: '1', name: 'Alice', status: 'pending' } // ✅
```
**Exception**: Non-serializable values are allowed in actions *if* a middleware (like `redux-thunk`) intercepts and consumes them before they reach the reducers.
## 5. Performance Considerations
Optimize your components to re-render only when necessary.
### 5.1. Use Memoized Selectors
Use `createSelector` (from RTK or Reselect) to create memoized selectors. These re-compute derived data only when their inputs change, preventing unnecessary component re-renders.
❌ **BAD: Inline selector in `useSelector` (can cause unnecessary re-renders)**
```javascript
// In a component
const activeUsers = useSelector(state =>
state.users.filter(user => user.isActive) // 🚨 New array reference on every render
);
```
✅ **GOOD: Memoized selector**
```javascript
// src/features/users/usersSelectors.js
import { createSelector } from '@reduxjs/toolkit';
const selectUsers = state => state.users;
export const selectActiveUsers = createSelector(
[selectUsers],
users => users.filter(user => user.isActive) // ✅ Only re-computes if users array changes
);
// In a component
const activeUsers = useSelector(selectActiveUsers);
```
### 5.2. Select Minimal Data
Components should select the smallest possible amount of data they need from the store. This reduces the chance of unnecessary re-renders.
❌ **BAD: Selecting entire slice**
```javascript
const user = useSelector(state => state.users); // 🚨 Re-renders if *any* user data changes
```
✅ **GOOD: Selecting specific data**
```javascript
const userName = useSelector(state => state.users.currentUser.name); // ✅ Re-renders only if name changes
```
## 6. Hooks Best Practices
Always use the pre-typed `useAppSelector` and `useAppDispatch` hooks for type safety and consistency.
### 6.1. Pre-Typed Hooks
Define and export pre-typed versions of `useSelector` and `useDispatch` in `src/app/hooks.js`. This provides compile-time type safety across your application.
```javascript
// src/app/hooks.js
import { useDispatch, useSelector } from 'react-redux';
// Import RootState and AppDispatch from your store
// (assuming store.js exports them for TypeScript)
// import type { RootState, AppDispatch } from './store';
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch; // as () => AppDispatch; (for TS)
export const useAppSelector = useSelector; // as <T>(selector: (state: RootState) => T) => T; (for TS)
```
### 6.2. Dispatch Actions Correctly
Use `useAppDispatch` to get the dispatch function and call your RTK-generated action creators.
```javascript
// In a component
import { useAppDispatch } from '@/app/hooks';
import { postAdded } from '@/features/posts/postsSlice';
const AddPostForm = () => {
const dispatch = useAppDispatch();
const handleSubmit = () => {
dispatch(postAdded('My Title', 'My Content', 'user123'));
};
// ...
};
```
## 7. Debugging
Leverage RTK's built-in debugging capabilities.
### 7.1. Redux DevTools
`configureStore` automatically sets up Redux DevTools integration. Ensure you have the browser extension installed.
### 7.2. Immutable State Invariant Middleware
In development, `configureStore` includes middleware that checks for accidental state mutations. Pay attention to console warnings. If you see them, fix the mutation immediately.