Class-to-Function Component Codemod
🚀 Transform React class components to modern functional components with hooks
This repository contains a powerful codemod that automatically converts React class components to functional components, handling complex transformations including state management, lifecycle methods, refs, and context usage.
✨ Features
- Complete class-to-function transformation - Converts
React.ComponentandReact.PureComponentto functional components - Smart state management - Transforms
this.stateandthis.setStatetouseStatehooks - Lifecycle method conversion - Converts
componentDidMount,componentDidUpdate, etc. touseEffecthooks - Ref handling - Transforms
createRefandthis.refNametouseRefhooks - Context integration - Converts
this.contexttouseContexthooks - Event handler optimization - Transforms class methods to optimized event handlers
- Optional AI Review - AI-powered code review and fixes (requires OpenAI API key)
- TypeScript support - Full TypeScript type preservation and enhancement
🚀 Quick Start
Basic Usage (No AI Required)
bash
AI-Enhanced Usage (Optional)
bash
📖 Detailed Usage
Command Options
| Option | Type | Default | Description |
|---|---|---|---|
--param autoAiReview=true | boolean | false | Enable AI code review (requires LLM_API_KEY) |
--target <PATH> | string | current directory | Directory to transform |
--dry-run | boolean | false | Preview changes without applying |
--verbose | boolean | false | Show detailed output |
Examples
Example 1: Simple Counter Component
Before:
tsx
After:
tsx
Example 2: Component with Context and Refs
Before:
tsx
After:
tsx
AI Review Features
When you enable AI review with --autoAiReview=true, the AI will:
- ✅ Fix dependency arrays in useEffect hooks
- ✅ Optimize event handlers with useCallback
- ✅ Add missing dependencies to prevent stale closures
- ✅ Improve performance with useMemo where appropriate
- ✅ Fix TypeScript types and add proper type annotations
- ✅ Format code according to best practices
- ✅ Detect and fix common React patterns
Setting up AI Review
-
Get an OpenAI API Key:
- Visit OpenAI Platform
- Create a new API key
- Copy the key
-
Set Environment Variable:
bash -
Run with AI:
bash
🛠️ Development
bash
🐛 Troubleshooting
Common Issues
"No files found to transform"
bash
"AI review failed"
bash
TypeScript compilation errors
bash
More Examples
For more detailed examples and advanced usage patterns, see USAGE.md.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
MIT License - see LICENSE file for details.