React Context API patterns for state sharing and prop drilling elimination
View on GitHubplugins/aai-stack-react/skills/react-context/SKILL.md
February 1, 2026
Select agents to install to:
npx add-skill https://github.com/the-answerai/alphaagent-team/blob/main/plugins/aai-stack-react/skills/react-context/SKILL.md -a claude-code --skill react-contextInstallation paths:
.claude/skills/react-context/# React Context Skill
Patterns for using React Context API effectively.
## Basic Context Pattern
### Creating Context
```tsx
interface ThemeContextValue {
theme: 'light' | 'dark'
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeContextValue | null>(null)
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light')
const toggleTheme = useCallback(() => {
setTheme(prev => prev === 'light' ? 'dark' : 'light')
}, [])
const value = useMemo(() => ({
theme,
toggleTheme,
}), [theme, toggleTheme])
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
)
}
// Custom hook for consuming context
function useTheme() {
const context = useContext(ThemeContext)
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider')
}
return context
}
```
### Using Context
```tsx
function ThemeToggle() {
const { theme, toggleTheme } = useTheme()
return (
<button onClick={toggleTheme}>
Current: {theme}
</button>
)
}
// App structure
function App() {
return (
<ThemeProvider>
<Header />
<Main />
<ThemeToggle />
</ThemeProvider>
)
}
```
## Context with Reducer
### Auth Context with Reducer
```tsx
interface AuthState {
user: User | null
loading: boolean
error: string | null
}
type AuthAction =
| { type: 'LOGIN_START' }
| { type: 'LOGIN_SUCCESS'; payload: User }
| { type: 'LOGIN_ERROR'; payload: string }
| { type: 'LOGOUT' }
function authReducer(state: AuthState, action: AuthAction): AuthState {
switch (action.type) {
case 'LOGIN_START':
return { ...state, loading: true, error: null }
case 'LOGIN_SUCCESS':
return { user: action.payload, loading: false, error: null }
case 'LOGIN_ERROR':
return { user: null, loading: false, error: action.payload }
case 'LOGOUT':
return { user: null, loading: false,