@incidental/project-templates
Version:
Claude Code template library for JavaScript projects with framework auto-detection
104 lines (80 loc) • 2.71 kB
Markdown
---
description: Add state management to React component using hooks or context
---
Add state management to a React component using hooks or React Context.
You are a React state management expert.
When the user requests state management via $ARGUMENTS, follow these guidelines:
1. **Determine the state scope:**
- Local component state: Use useState or useReducer
- Shared state across components: Use Context API
- Complex state logic: Use useReducer
- Server state: Suggest React Query or SWR
2. **For local state (useState):**
```typescript
import { useState } from 'react'
function Component() {
const [value, setValue] = useState<Type>(initialValue)
const handleChange = (newValue: Type) => {
setValue(newValue)
}
return // JSX using value and handleChange
}
```
3. **For complex state (useReducer):**
```typescript
import { useReducer } from 'react'
type State = { /* state shape */ }
type Action =
| { type: 'ACTION_ONE'; payload: any }
| { type: 'ACTION_TWO'; payload: any }
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'ACTION_ONE':
return { ...state, /* updates */ }
default:
return state
}
}
function Component() {
const [state, dispatch] = useReducer(reducer, initialState)
// Use state and dispatch
}
```
4. **For global state (Context):**
```typescript
import { createContext, useContext, useState } from 'react'
interface ContextType {
value: any
setValue: (value: any) => void
}
const MyContext = createContext<ContextType | undefined>(undefined)
export function MyProvider({ children }: { children: React.ReactNode }) {
const [value, setValue] = useState(initialValue)
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
)
}
export function useMyContext() {
const context = useContext(MyContext)
if (!context) {
throw new Error('useMyContext must be used within MyProvider')
}
return context
}
```
5. **Best practices:**
- Keep state as local as possible
- Use TypeScript for state types
- Memoize expensive computations with useMemo
- Memoize callbacks with useCallback when needed
- Consider splitting large contexts into smaller ones
6. **After adding state:**
- Explain the state structure
- Show how to use the state in components
- Suggest optimization opportunities
- Recommend adding tests for state logic
**Target:** $ARGUMENTS (component name or state requirement)