Redux Toolkit
You are an expert in Redux Toolkit for state management in React and Next.js applications.
Development Philosophy
- Write clean, maintainable, and scalable code
- Adhere to SOLID principles
- Favor functional and declarative programming patterns
- Emphasize type safety and component-driven approaches
Redux State Management
Core Principles
- Implement Redux Toolkit for global state management
- Use createSlice to define state, reducers, and actions together
- Normalize state structure to prevent deeply nested data
- Employ selectors to encapsulate state access
- Separate concerns by feature; avoid monolithic slices
Slice Structure
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
interface CounterState {
value: number
isLoading: boolean
}
const initialState: CounterState = {
value: 0,
isLoading: false,
}
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1
},
setLoading: (state, action: PayloadAction<boolean>) => {
state.isLoading = action.payload
},
},
})
export const { increment, setLoading } = counterSlice.actions
export default counterSlice.reducer
Naming Conventions
- PascalCase: Components, type definitions, interfaces
- kebab-case: Directory and file names
- camelCase: Variables, functions, methods, hooks, properties
- UPPERCASE: Environment variables, constants
Prefixes
- Event handlers:
handle (e.g., handleClick)
- Boolean variables: verbs (e.g.,
isLoading, hasError)
- Custom hooks:
use (e.g., useAuth)
TypeScript Integration
- Enable strict mode
- Define clear interfaces for props and Redux state structure
- Apply generics where type flexibility is needed
- Prefer interfaces over types for object structures
- Use typed hooks (
useAppDispatch, useAppSelector)
Async Operations
RTK Query
- Use RTK Query for data fetching and caching
- Define API slices with endpoints
- Leverage automatic cache invalidation
- Implement optimistic updates when appropriate
createAsyncThunk
export const fetchUser = createAsyncThunk(
'user/fetch',
async (userId: string, { rejectWithValue }) => {
try {
const response = await api.getUser(userId)
return response.data
} catch (error) {
return rejectWithValue(error.message)
}
}
)
Performance Optimization
- Use React.memo() strategically
- Implement useCallback for memoized functions
- Apply useMemo for expensive computations
- Avoid inline function definitions in JSX
- Use dynamic imports for code splitting
- Employ proper keys in lists (avoid index-based keys)
Selectors
- Create memoized selectors with createSelector
- Encapsulate state shape in selectors
- Compose selectors for derived data
- Avoid computing in components
Error Handling
- Implement error boundaries with external logging
- Use Zod for validation
- Handle async errors in thunks
- Provide user-friendly error messages
Testing
- Apply Jest and React Testing Library
- Follow Arrange-Act-Assert patterns
- Mock external dependencies
- Test reducers, selectors, and thunks independently
1---2name: redux-toolkit3description: Comprehensive Redux Toolkit best practices for React and Next.js applications with TypeScript.4metadata:5 maintainer: Mindrally6 source: https://skillmd.com/skills/mindrally/redux-toolkit7 upstream: https://github.com/Mindrally/skills8---910# Redux Toolkit1112You are an expert in Redux Toolkit for state management in React and Next.js applications.1314## Development Philosophy1516- Write clean, maintainable, and scalable code17- Adhere to SOLID principles18- Favor functional and declarative programming patterns19- Emphasize type safety and component-driven approaches2021## Redux State Management2223### Core Principles24- Implement Redux Toolkit for global state management25- Use createSlice to define state, reducers, and actions together26- Normalize state structure to prevent deeply nested data27- Employ selectors to encapsulate state access28- Separate concerns by feature; avoid monolithic slices2930### Slice Structure31```typescript32import { createSlice, PayloadAction } from '@reduxjs/toolkit'3334interface CounterState {35 value: number36 isLoading: boolean37}3839const initialState: CounterState = {40 value: 0,41 isLoading: false,42}4344const counterSlice = createSlice({45 name: 'counter',46 initialState,47 reducers: {48 increment: (state) => {49 state.value += 150 },51 setLoading: (state, action: PayloadAction<boolean>) => {52 state.isLoading = action.payload53 },54 },55})5657export const { increment, setLoading } = counterSlice.actions58export default counterSlice.reducer59```6061## Naming Conventions6263- **PascalCase**: Components, type definitions, interfaces64- **kebab-case**: Directory and file names65- **camelCase**: Variables, functions, methods, hooks, properties66- **UPPERCASE**: Environment variables, constants6768### Prefixes69- Event handlers: `handle` (e.g., `handleClick`)70- Boolean variables: verbs (e.g., `isLoading`, `hasError`)71- Custom hooks: `use` (e.g., `useAuth`)7273## TypeScript Integration7475- Enable strict mode76- Define clear interfaces for props and Redux state structure77- Apply generics where type flexibility is needed78- Prefer interfaces over types for object structures79- Use typed hooks (`useAppDispatch`, `useAppSelector`)8081## Async Operations8283### RTK Query84- Use RTK Query for data fetching and caching85- Define API slices with endpoints86- Leverage automatic cache invalidation87- Implement optimistic updates when appropriate8889### createAsyncThunk90```typescript91export const fetchUser = createAsyncThunk(92 'user/fetch',93 async (userId: string, { rejectWithValue }) => {94 try {95 const response = await api.getUser(userId)96 return response.data97 } catch (error) {98 return rejectWithValue(error.message)99 }100 }101)102```103104## Performance Optimization105106- Use React.memo() strategically107- Implement useCallback for memoized functions108- Apply useMemo for expensive computations109- Avoid inline function definitions in JSX110- Use dynamic imports for code splitting111- Employ proper keys in lists (avoid index-based keys)112113## Selectors114115- Create memoized selectors with createSelector116- Encapsulate state shape in selectors117- Compose selectors for derived data118- Avoid computing in components119120## Error Handling121122- Implement error boundaries with external logging123- Use Zod for validation124- Handle async errors in thunks125- Provide user-friendly error messages126127## Testing128129- Apply Jest and React Testing Library130- Follow Arrange-Act-Assert patterns131- Mock external dependencies132- Test reducers, selectors, and thunks independently