npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-feature-generator

v1.0.0

Published

CLI tool to generate React TypeScript feature scaffolding

Downloads

44

Readme

React Feature Generator - Examples

This document provides comprehensive examples of using the React Feature Generator CLI.

Table of Contents

Basic Feature Generation

1. Simple Feature

# Generate a basic feature
generate-feature feature notifications

# Generated structure:
# src/features/notifications/
# ├── services/notifications-service.ts
# ├── repositories/notifications-repository.ts
# ├── forms/schema.ts
# ├── types/index.ts
# ├── store/notifications-store.ts
# ├── routes/notifications-routes.tsx
# ├── layouts/notifications-layout.tsx
# └── README.md

2. Feature with Custom Path

# Generate in custom directory
generate-feature feature auth --path src/modules

# Generated in: src/modules/auth/

3. Minimal Feature (No Types/Store)

# Generate without types and store
generate-feature feature utils --no-types --no-store

Service Generation

1. Basic GET Service

generate-feature service users getUserProfile
# Prompts will guide you through:
# ✓ HTTP Method: GET
# ✓ Endpoint: /users/profile
# ✓ Parameters: No
# ✓ Return Type: User

# Generated in users-service.ts:
export async function getUserProfile() {
    const response = await http.get<TApiResponse<User>>("/users/profile");
    return response.data;
}

2. Search Service with Parameters

generate-feature service products searchProducts
# Interactive prompts:
# ? Select HTTP method: GET
# ? API endpoint: /products/search
# ? Does this service accept parameters? Yes
# ? Return type: Product[]

# Generated:
export async function searchProducts(params?: any) {
    const response = await http.get<TApiResponse<Product[]>>("/products/search", { params });
    return response.data;
}

3. POST Service for Creation

generate-feature service orders createOrder
# Prompts:
# ? Select HTTP method: POST
# ? API endpoint: /orders
# ? Does this service accept parameters? Yes
# ? Return type: Order

# Generated:
export async function createOrder(input: any) {
    const response = await http.post<TApiResponse<Order>>("/orders", input);
    return response.data;
}

4. DELETE Service with ID

generate-feature service users deleteUser
# Prompts:
# ? Select HTTP method: DELETE
# ? API endpoint: /users/:id
# ? Does this service accept parameters? Yes
# ? Return type: null

# Generated:
export async function deleteUser(id: string) {
    const response = await http.delete<TApiResponse<null>>(`/users/${id}`);
    return response.data;
}

5. File Upload Service

generate-feature service media uploadImage
# Prompts:
# ? Select HTTP method: POST
# ? API endpoint: /media/upload
# ? Does this service accept parameters? Yes
# ? Return type: MediaFile

# Generated:
export async function uploadImage(input: any) {
    const response = await http.post<TApiResponse<MediaFile>>("/media/upload", input);
    return response.data;
}

Repository Hook Generation

1. Query Hook for Data Fetching

generate-feature repo users useUserProfile
# Prompts:
# ? Select hook type: Query (useQuery)
# ? Service function name: getUserProfile
# ? Include success callback parameter? No
# ? Include toast error handling? Yes

# Generated:
export function useUserProfile(params?: any, options?: any) {
    const { isLoading, isFetching, data, error, refetch } = useQuery({
        queryKey: ["userprofile", params],
        queryFn: () => getUserProfile(params),
        enabled: params !== undefined,
        ...options
    });

    return { 
        isLoading, 
        isFetching, 
        data: data?.results, 
        error,
        refetch
    };
}

2. Mutation Hook for Data Modification

generate-feature repo orders useCreateOrder
# Prompts:
# ? Select hook type: Mutation (useMutation)
# ? Service function name: createOrder
# ? Include success callback parameter? Yes
# ? Include toast error handling? Yes

# Generated:
export function useCreateOrder(
    onSuccess?: TSuccess<TApiResponse<any>>
) {
    const queryClient = useQueryClient();
    
    return useMutation({
        mutationFn: createOrder,
        onSuccess: (res) => {
            toast.success("Operation completed successfully");
            queryClient.invalidateQueries({ queryKey: ["createorder"] });
            onSuccess && onSuccess(res);
        },
        onError: (error: TErrorMessage) => {
            toast.error(error.response?.data.message ?? "Operation failed");
        },
    });
}

3. Infinite Query Hook for Pagination

generate-feature repo products useProductsInfinite
# Prompts:
# ? Select hook type: Infinite Query (useInfiniteQuery)
# ? Service function name: getProducts
# ? Include success callback parameter? No
# ? Include toast error handling? Yes

# Generated with pagination logic:
export function useProductsInfinite(params?: any) {
    const {
        data,
        isLoading,
        isFetching,
        fetchNextPage,
        hasNextPage,
        isFetchingNextPage,
        error
    } = useInfiniteQuery({
        queryKey: ["productsinfinite", params],
        queryFn: ({ pageParam = 1 }) => getProducts({ ...params, page: pageParam }),
        getNextPageParam: (lastPage, pages) => {
            if (lastPage.results?.pagination?.hasMore) {
                return pages.length + 1;
            }
            return undefined;
        },
    });

    const allData = data?.pages.flatMap(page => page.results?.data || []) || [];

    return {
        data: allData,
        isLoading,
        isFetching,
        fetchNextPage,
        hasNextPage,
        isFetchingNextPage,
        error,
        totalCount: data?.pages[0]?.results?.pagination?.total || 0
    };
}

Real-world Scenarios

Scenario 1: E-commerce Product Management

# 1. Generate base feature
generate-feature feature products

# 2. Add search functionality
generate-feature service products searchProducts
# GET /products/search with query parameters

generate-feature repo products useSearchProducts
# Query hook with debounced search

# 3. Add category filtering
generate-feature service products getProductsByCategory
# GET /products/category/:categoryId

generate-feature repo products useProductsByCategory
# Query hook for category-based filtering

# 4. Add bulk operations
generate-feature service products bulkUpdateProducts
# PUT /products/bulk

generate-feature repo products useBulkUpdateProducts
# Mutation hook for bulk updates

# 5. Add analytics
generate-feature service products getProductAnalytics
# GET /products/analytics

generate-feature repo products useProductAnalytics
# Query hook for analytics data

Scenario 2: User Management System

# 1. Generate user feature
generate-feature feature users

# 2. Add user search
generate-feature service users searchUsers
generate-feature repo users useSearchUsers

# 3. Add role management
generate-feature service users updateUserRole
generate-feature repo users useUpdateUserRole

# 4. Add user activity tracking
generate-feature service users getUserActivity
generate-feature repo users useUserActivity

# 5. Add bulk user operations
generate-feature service users bulkInviteUsers
generate-feature repo users useBulkInviteUsers

Scenario 3: File Management

# 1. Generate files feature
generate-feature feature files

# 2. Add file upload with progress
generate-feature service files uploadFile
generate-feature repo files useUploadFile

# 3. Add file preview
generate-feature service files getFilePreview
generate-feature repo files useFilePreview

# 4. Add file sharing
generate-feature service files shareFile
generate-feature repo files useShareFile

# 5. Add folder operations
generate-feature service files createFolder
generate-feature repo files useCreateFolder

Advanced Patterns

1. Optimistic Updates

# Generate mutation with optimistic updates
generate-feature repo posts useLikePost
# Manually customize for optimistic UI updates

# In the generated hook, add:
onMutate: async (postId) => {
    await queryClient.cancelQueries({ queryKey: ['posts'] });
    const previousPosts = queryClient.getQueryData(['posts']);
    
    queryClient.setQueryData(['posts'], (old: any) => 
        old.map((post: any) => 
            post.id === postId 
                ? { ...post, likes: post.likes + 1, isLiked: true }
                : post
        )
    );
    
    return { previousPosts };
},
onError: (err, variables, context) => {
    queryClient.setQueryData(['posts'], context?.previousPosts);
},

2. Real-time Updates with WebSocket

# Generate base service and hook
generate-feature service notifications getNotifications
generate-feature repo notifications useNotifications

# Manually add WebSocket integration:
export function useRealtimeNotifications() {
    const queryClient = useQueryClient();
    
    useEffect(() => {
        const ws = new WebSocket('ws://localhost:8080');
        
        ws.onmessage = (event) => {
            const notification = JSON.parse(event.data);
            queryClient.setQueryData(['notifications'], (old: any) => 
                [notification, ...(old || [])]
            );
        };
        
        return () => ws.close();
    }, [queryClient]);
    
    return useNotifications();
}

3. Complex State Management

# Generate feature with store
generate-feature feature dashboard

# Enhance the generated store for complex state:
export const dashboardStore = proxy({
    activeTab: 'overview',
    filters: {
        dateRange: 'last7days',
        category: 'all',
        status: 'active'
    },
    data: {
        overview: null,
        analytics: null,
        reports: null
    },
    
    // Actions
    setActiveTab(tab: string) {
        this.activeTab = tab;
    },
    
    updateFilters(newFilters: Partial<typeof this.filters>) {
        Object.assign(this.filters, newFilters);
    },
    
    setData(key: string, data: any) {
        this.data[key] = data;
    }
});

4. Error Boundary Integration

# Generate services with custom error handling
generate-feature service users getUserData
generate-feature repo users useUserData

# Customize error handling:
export function useUserData(userId: string) {
    return useQuery({
        queryKey: ['user', userId],
        queryFn: () => getUserData(userId),
        onError: (error) => {
            // Custom error logging
            console.error('User data fetch failed:', error);
            
            // Report to error service
            reportError(error, { userId, context: 'user-data-fetch' });
        },
        retry: (failureCount, error) => {
            // Custom retry logic
            if (error.response?.status === 404) return false;
            return failureCount < 3;
        }
    });
}

5. Performance Optimization

# Generate with prefetching
generate-feature service products getProductDetails
generate-feature repo products useProductDetails

# Add prefetching logic:
export function usePrefetchProductDetails() {
    const queryClient = useQueryClient();
    
    return useCallback((productId: string) => {
        queryClient.prefetchQuery({
            queryKey: ['product', productId],
            queryFn: () => getProductDetails(productId),
            staleTime: 5 * 60 * 1000, // 5 minutes
        });
    }, [queryClient]);
}

CLI Command Shortcuts

# Quick commands for common patterns
generate-feature f auth                          # Generate auth feature
generate-feature s auth login                    # Add login service
generate-feature r auth useLogin                 # Add login hook

generate-feature f products --no-store           # Feature without store
generate-feature s products search --method GET  # Search service
generate-feature r products useSearch --type query # Search hook

# Batch generation for complete CRUD
generate-feature f orders
generate-feature s orders createOrder --method POST
generate-feature s orders updateOrder --method PUT  
generate-feature s orders deleteOrder --method DELETE
generate-feature r orders useCreateOrder --type mutation
generate-feature r orders useUpdateOrder --type mutation
generate-feature r orders useDeleteOrder --type mutation

Tips and Best Practices

  1. Naming Conventions: Use descriptive names for services and hooks
  2. Service Parameters: Always consider what parameters your API endpoints need
  3. Error Handling: Enable toast error handling for better UX
  4. Type Safety: Update the generated return types to match your API
  5. Query Keys: Customize query keys for better cache management
  6. Success Callbacks: Use success callbacks for navigation or additional actions

For more advanced customization, check the generated files and modify them according to your specific requirements.