Skill v1.0.1
currentAutomated scan100/1001 files
version: "1.0.1" name: libraries-dependencies-mastery description: Complete mastery of essential modern web development libraries and dependencies. Cover Next.js, React, TypeScript, Tailwind CSS, Firebase, Zustand, redux-toolkit, react-hook-form, Zod, shadcn/ui, lucide-react, Stripe, and more. Learn setup, integration patterns, advanced usage, performance optimization, troubleshooting, common pitfalls, and version management. Includes quick reference guides, in-depth tutorials, complete examples for e-commerce and SaaS, configuration files, type definitions, error handling, and production patterns. Master how libraries work together and solve real-world challenges.
Libraries & Dependencies Mastery
Overview
You are an expert in modern web development libraries and their integration. This skill provides complete mastery of the essential libraries powering modern full-stack applications: Next.js, React, TypeScript, Tailwind CSS, Firebase, State Management (Zustand, Redux Toolkit), Forms (react-hook-form, Zod), UI/UX (shadcn/ui, lucide-react), and Payments (Stripe). Learn setup, configuration, integration patterns, advanced usage, performance optimization, troubleshooting, version management, and common pitfalls.
Core Library Mastery
1. Next.js 13+ Complete Mastery
Setup & Configuration:
- Installation and project initialization
- tsconfig.json configuration for strict TypeScript
- next.config.js customization
- Environment variables (.env, .env.local, .env.production)
- Path aliases (@/ imports)
- Monorepo setup with workspaces
App Router (Next.js 13+):
- File-based routing structure
- Route segments and dynamic routes ([id], [...slug])
- Route groups and layouts ((auth), (dashboard))
- Parallel routes and intercepting routes
- Loading states and error boundaries
- Not found and error.js pages
- Middleware and request handling
- Route handlers (GET, POST, PUT, DELETE, PATCH)
- Server Components vs Client Components
- Suspense and streaming
- Data fetching patterns (fetch, cache tags)
- Revalidation strategies (ISR, on-demand)
Performance Optimization:
- Image optimization with next/image
- Font optimization
- Script optimization and loading strategies
- Dynamic imports with React.lazy
- Code splitting and bundle analysis
- CSS optimization and minification
- Compression and gzip
- CDN configuration
Common Pitfalls & Solutions:
- Hydration mismatches (Server vs Client)
- Using client-only features in Server Components
- Incorrect caching strategies
- Image optimization issues
- Font loading performance
- Dynamic routes not rendering statically
- Environment variable scope
Troubleshooting Guide:
Issue: "Cannot find module" in buildsSolution: Check tsconfig paths, clear .next folder, rebuildIssue: Hydration mismatch errorSolution: Use dynamic imports, wrap client code, check useEffectIssue: Images not optimizingSolution: Use next/image, configure domains, check sizesIssue: Build time too longSolution: Analyze with `next/bundle-analyzer`, use dynamic importsIssue: Environment variables undefinedSolution: Prefix with NEXT_PUBLIC_ for client, restart dev server
Version Management:
- Upgrading from Pages Router to App Router
- Breaking changes between versions
- Migration guides
- Beta features and deprecations
- Staying updated with releases
2. React 18+ Complete Mastery
Hooks Deep Dive:
- useState: State management, state updates, batching
- useEffect: Side effects, cleanup, dependencies, common pitfalls
- useContext: Context creation, avoiding prop drilling
- useReducer: Complex state logic, reducer patterns
- useCallback: Memoization, dependency arrays
- useMemo: Expensive computations, memory management
- useRef: DOM access, persistent values, .current
- useLayoutEffect: DOM layout measurements
- useTransition: Concurrent rendering, isPending state
- useDeferredValue: Value debouncing, input optimization
- useId: Unique identifiers, accessibility
- useImperativeHandle: Custom instance values
Component Patterns:
- Functional components with hooks
- Custom hooks development and reusability
- Compound components
- Render props pattern
- Higher-order components
- Provider pattern
- Controlled vs uncontrolled components
- Composition over inheritance
Performance Optimization:
- React.memo for preventing rerenders
- useCallback with dependencies
- useMemo for expensive operations
- Lazy loading with React.lazy and Suspense
- Code splitting strategies
- List rendering with keys (importance of stable keys)
- Avoiding unnecessary renders
- Profiler API for performance measurement
Concurrent Features:
- Suspense boundaries
- useTransition for non-blocking updates
- useDeferredValue for value debouncing
- Streaming and progressive rendering
- Automatic batching of state updates
Common Pitfalls & Solutions:
- Missing dependency in useEffect
- Stale closures in hooks
- Memory leaks in useEffect
- Infinite loops with useEffect
- Using hooks conditionally
- Not returning cleanup functions
- Incorrect memo dependencies
- State batching confusion
Troubleshooting Guide:
Issue: Infinite loop in useEffectSolution: Check dependencies, add return cleanup functionIssue: Stale state in callbackSolution: Include state in dependencies or use useCallbackIssue: Memory leak warningSolution: Add cleanup function to useEffect, unsubscribeIssue: Component rerending unnecessarilySolution: Use React.memo, useCallback, useMemoIssue: Hydration error with useIdSolution: Use proper key prop, wrap in Suspense
3. TypeScript Complete Mastery
Fundamentals:
- Primitive types (string, number, boolean, null, undefined)
- Union types and intersection types
- Type literals and literal types
- Enums and const assertions
- Type aliases vs interfaces
- Extending types and interfaces
- Optional properties (?) and nullish coalescing (??)
Advanced Types:
- Generic types and constraints
- Conditional types (extends ? :)
- Mapped types (Record, Partial, Required, etc.)
- Utility types (Pick, Omit, Exclude, Extract, etc.)
- Discriminated unions for exhaustive checking
- Type guards and type predicates (is keyword)
- Const type parameters
- Template literal types
React + TypeScript:
- Component prop typing
- Event handler typing
- Ref typing with Ref<HTMLInputElement>
- useState with initial values and TypeScript
- useReducer with typed actions
- useContext with typed values
- Custom hook typing
- Children prop typing
Common Patterns:
// Discriminated uniontype Action =| { type: 'ADD'; payload: Item }| { type: 'REMOVE'; payload: string };// Generic componentfunction List<T extends { id: string }>(props: { items: T[] }) {}// Type guardfunction isString(value: unknown): value is string {return typeof value === 'string';}// Utility type usagetype User = { name: string; age: number; email: string };type UserPreview = Pick<User, 'name' | 'age'>;
Configuration:
- tsconfig.json strict mode
- CompilerOptions for strict type checking
- Path mapping and aliases
- Module resolution settings
- Declaration file generation
Common Pitfalls & Solutions:
- Type inference failures
- Type assertion misuse
- Any type overuse
- Incorrect generic constraints
- Missing type definitions
- Circular type dependencies
Troubleshooting Guide:
Issue: Type 'X' is not assignable to type 'Y'Solution: Check property names, use type assertion carefully, review interfacesIssue: Cannot find name 'X'Solution: Check imports, verify tsconfig paths, check node_modulesIssue: Property 'X' doesn't exist on type 'Y'Solution: Check types, update interfaces, verify external package typesIssue: Generic type 'T' is too complexSolution: Add constraints, break into simpler types, use keyof
4. Tailwind CSS Complete Mastery
Core Concepts:
- Utility-first CSS methodology
- JIT (Just-In-Time) compilation
- Responsive design with breakpoints (sm, md, lg, xl, 2xl)
- Hover, focus, and other state variants
- Dark mode implementation (class and prefers-color-scheme)
- Custom configuration (colors, spacing, fonts)
- Arbitrary values ([width: 343px])
- CSS layers and specificity
Configuration & Customization:
// tailwind.config.tsimport type { Config } from 'tailwindcss'export default {content: ['./app/**/*.{js,ts,jsx,tsx}','./components/**/*.{js,ts,jsx,tsx}',],theme: {extend: {colors: {primary: '#your-color',},spacing: {'128': '32rem',},},},plugins: [],} satisfies Config
Advanced Patterns:
- Responsive design strategies
- Component extraction with @apply
- Conditional styling with clsx/classnames
- Dark mode toggling
- Custom plugins
- CSS variables integration
- Animation and transition utilities
- Theme switching with CSS custom properties
Performance Optimization:
- Purging unused styles in production
- Content configuration for tree-shaking
- CSS size analysis
- Critical CSS inline optimization
- Lazy loading stylesheets
- CSS compression
Common Pitfalls & Solutions:
- Utility conflicts and specificity issues
- Unresponsive images with Tailwind sizing
- Dark mode not working properly
- Build process including unused classes
- Custom color not applying
- Conflicting CSS and Tailwind classes
Troubleshooting Guide:
Issue: Styles not applying in productionSolution: Check content paths, rebuild, check purge configIssue: Dark mode not togglingSolution: Set darkMode: 'class' in config, add class to htmlIssue: Custom colors not availableSolution: Update tailwind.config.ts theme.extend.colorsIssue: Build size too largeSolution: Verify content paths, use JIT, remove unused pluginsIssue: Responsive styles not workingSolution: Use correct breakpoint prefix (sm:, md:), check cascade
5. Firebase Complete Mastery
Setup & Configuration:
// lib/firebase.tsimport { initializeApp } from 'firebase/app';import { getAuth } from 'firebase/auth';import { getFirestore } from 'firebase/firestore';import { getStorage } from 'firebase/storage';const firebaseConfig = {apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,};const app = initializeApp(firebaseConfig);export const auth = getAuth(app);export const db = getFirestore(app);export const storage = getStorage(app);
Authentication:
- Email/password signup and signin
- OAuth providers (Google, GitHub, Facebook)
- User profile management
- Custom claims for authorization
- Session persistence
- Token refresh and expiration
- MFA setup and verification
- Anonymous authentication
Firestore Database:
- Collection references and document references
- CRUD operations (create, read, update, delete)
- Real-time listeners with cleanup
- Batch writes and transactions
- Query operations (where, orderBy, limit)
- Pagination with startAt/endAt
- Subcollections vs root collections
- Data modeling and normalization
Cloud Storage:
- File upload with progress tracking
- Download URLs and signed URLs
- File deletion and management
- Access control and security rules
- Image optimization strategies
- Resumable uploads for large files
Offline Persistence:
- Local caching configuration
- Sync with server on reconnection
- Offline-first strategies
- Conflict resolution
Common Pitfalls & Solutions:
- Security rules blocking access
- Missing .onSnapshot cleanup
- Querying with unstable data
- Creating too many subcollections
- Not validating data before writes
- Inconsistent authentication state
- Storage rules preventing uploads
Troubleshooting Guide:
Issue: "Permission denied" errorsSolution: Check Security Rules, verify auth state, check custom claimsIssue: onSnapshot not updatingSolution: Verify listener attached, check firestore rules, cleanup properlyIssue: File upload failingSolution: Check storage rules, verify file path, check bucket permissionsIssue: Auth state undefined on refreshSolution: Wait for onAuthStateChanged before rendering, use loading stateIssue: Realtime listener consuming quotaSolution: Limit listeners, use oncemore, implement cleanup
6. State Management: Zustand & Redux Toolkit
Zustand Complete:
// store/cartStore.tsimport { create } from 'zustand';import { persist } from 'zustand/middleware';interface CartState {items: CartItem[];addItem: (item: CartItem) => void;removeItem: (id: string) => void;getTotal: () => number;}export const useCartStore = create<CartState>()(persist((set, get) => ({items: [],addItem: (item) => set(state => ({items: [...state.items, item]})),removeItem: (id) => set(state => ({items: state.items.filter(i => i.id !== id)})),getTotal: () => {return get().items.reduce((sum, item) =>sum + item.price * item.quantity, 0);},}),{ name: 'cart-storage' }));
Redux Toolkit Complete:
// store/cartSlice.tsimport { createSlice, PayloadAction } from '@reduxjs/toolkit';interface CartState {items: CartItem[];}const cartSlice = createSlice({name: 'cart',initialState: { items: [] },reducers: {addItem: (state, action: PayloadAction<CartItem>) => {state.items.push(action.payload);},removeItem: (state, action: PayloadAction<string>) => {state.items = state.items.filter(i => i.id !== action.payload);},},});export const { addItem, removeItem } = cartSlice.actions;export default cartSlice.reducer;
Comparison & When to Use:
- Zustand: Lightweight, minimal boilerplate, easier for beginners
- Redux Toolkit: More powerful, better DevTools, larger apps
- Integration with other libraries
- Performance considerations
Common Pitfalls & Solutions:
- Mutating state directly in Zustand
- Not using persist middleware properly
- Redux selector performance issues
- Unnecessary renders from store changes
- DevTools not working
Troubleshooting Guide:
Issue: State not persisting in ZustandSolution: Add persist middleware, check localStorage, verify name propIssue: Redux component not updatingSolution: Check selector, verify dispatch called, check middlewareIssue: Store data undefined on mountSolution: Use loading state, wait for hydration, check persistIssue: Memory leaks from listenersSolution: Return unsubscribe function, cleanup in useEffect
7. Forms: react-hook-form + Zod
react-hook-form Setup:
import { useForm } from 'react-hook-form';import { zodResolver } from '@hookform/resolvers/zod';import { z } from 'zod';const schema = z.object({email: z.string().email(),password: z.string().min(8),});type FormData = z.infer<typeof schema>;function LoginForm() {const { register, handleSubmit, formState: { errors } } = useForm<FormData>({resolver: zodResolver(schema),});return (<form onSubmit={handleSubmit(onSubmit)}><input {...register('email')} />{errors.email && <span>{errors.email.message}</span>}</form>);}
Zod Validation:
// Complete validation schemaconst userSchema = z.object({name: z.string().min(2).max(50),email: z.string().email(),age: z.number().min(18).max(120),password: z.string().min(8),confirmPassword: z.string(),terms: z.boolean().refine(val => val === true),}).refine(data => data.password === data.confirmPassword, {message: "Passwords don't match",path: ["confirmPassword"],});
Advanced Patterns:
- Multi-step forms with validation
- Dynamic field arrays
- Conditional field rendering
- Async validation (checking email availability)
- Custom validators
- Nested object validation
- File upload validation
- Form submission handling
Common Pitfalls & Solutions:
- Form not submitting with validation errors
- Async validation causing delays
- Zod schema not matching form structure
- Field array complexity
- Custom validation logic errors
- Form reset not working
- File upload validation failing
Troubleshooting Guide:
Issue: Form submitting even with errorsSolution: Check handleSubmit usage, verify resolver setupIssue: Async validation taking too longSolution: Add debounce, implement caching, optimize backendIssue: Zod error: "Expected object, received undefined"Solution: Verify schema matches form data structureIssue: Dynamic fields not validatingSolution: Use z.array() properly, update schema dynamicallyIssue: File validation not workingSolution: Use refine/superRefine, check file type validation
8. UI/UX: shadcn/ui & lucide-react
shadcn/ui Setup & Usage:
// Using pre-built componentsimport { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Card } from '@/components/ui/card';export function MyComponent() {return (<Card><Input placeholder="Enter text" /><Button>Submit</Button></Card>);}
Available Components:
- Buttons (variants, sizes, states)
- Input fields and forms
- Cards and containers
- Modals and dialogs
- Dropdowns and menus
- Tabs and accordions
- Data tables and lists
- Alerts and notifications
- Progress indicators
- Navigation components
- Tooltips and popovers
lucide-react Icons:
import { Heart, ShoppingCart, Menu, X } from 'lucide-react';export function IconExample() {return (<><Heart size={24} /><ShoppingCart className="text-blue-600" /><Menu strokeWidth={1.5} /></>);}
Customization & Theming:
- Tailwind CSS integration
- Color customization
- Size variants
- Animation options
- Dark mode support
- Custom component wrappers
Common Pitfalls & Solutions:
- Component styling conflicts
- Icon size inconsistencies
- Accessibility issues
- Theme not applying
- Custom styling overriding defaults
Troubleshooting Guide:
Issue: shadcn/ui component styles not applyingSolution: Check Tailwind config, verify CSS import, check className conflictsIssue: Icons not showing or sizing incorrectlySolution: Specify size prop, check import path, verify CSS classesIssue: Dark mode not working with componentsSolution: Set darkMode in tailwind.config, wrap with providerIssue: Component variants not workingSolution: Check component prop names, verify version compatibility
9. Payments: Stripe Integration
Stripe Setup:
import Stripe from 'stripe';const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);// Create payment intentconst paymentIntent = await stripe.paymentIntents.create({amount: 1000, // in centscurrency: 'usd',payment_method_types: ['card'],});
Client-Side Integration:
import { loadStripe } from '@stripe/js';import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_KEY!);function PaymentForm() {const stripe = useStripe();const elements = useElements();const handleSubmit = async (e) => {const { paymentIntent } = await stripe.confirmCardPayment(clientSecret,{ payment_method: { card: elements.getElement(CardElement) } });};return (<Elements stripe={stripePromise}><CardElement /><button onClick={handleSubmit}>Pay</button></Elements>);}
Webhooks & Server-Side:
- Payment intent creation
- Webhook event handling
- Subscription management
- Customer management
- Invoice generation
- Refund processing
Common Pitfalls & Solutions:
- Missing publishable key environment variable
- Webhook signature verification failing
- Race conditions with payment status
- PCI compliance violations
- Testing with wrong API keys
- Missing error handling
- Race conditions in webhook processing
Troubleshooting Guide:
Issue: "publishable key not found" errorSolution: Check NEXT_PUBLIC_STRIPE_KEY env var, restart dev serverIssue: Webhook verification failingSolution: Use correct webhook secret, check signature encodingIssue: Payment processing twiceSolution: Implement idempotency keys, add retry logic, check order statusIssue: Test card not workingSolution: Use Stripe test cards (4242424242424242), check mode (test/live)
10. Other Essential Libraries
react-hot-toast:
import toast from 'react-hot-toast';// Success toasttoast.success('Order placed successfully!');// Error toasttoast.error('Payment failed');// Custom toasttoast((t) => (<div>Custom message<button onClick={() => toast.dismiss(t.id)}>Dismiss</button></div>));
axios vs fetch:
// axios - automatic JSON handling, interceptorsimport axios from 'axios';const response = await axios.get('/api/products');// fetch - native, no dependenciesconst response = await fetch('/api/products');const data = await response.json();
clsx/classnames:
import clsx from 'clsx';const buttonClass = clsx('px-4 py-2 rounded',variant === 'primary' && 'bg-blue-600 text-white',variant === 'secondary' && 'bg-gray-200 text-gray-900',isLoading && 'opacity-50 cursor-not-allowed');
Integration Patterns: Libraries Working Together
E-Commerce Example
// Components use shadcn/ui + lucide-react// Forms use react-hook-form + Zod// State with Zustand + persist// API calls with axios// Payments with Stripe// Database with Firebase// Styling with Tailwind CSS// Routing with Next.js
SaaS Example
// Next.js for routing + SSR// React for components// TypeScript for type safety// Firebase Auth + Firestore// Redux Toolkit for complex state// Tailwind + shadcn/ui for UI// react-hook-form for user forms// Stripe for subscriptions
Dependency Management
package.json Best Practices:
- Version pinning strategies
- Semantic versioning
- Peer dependencies
- Dev vs production dependencies
- Monorepo workspaces
- Script automation
Updating Dependencies:
# Check outdated packagesnpm outdated# Update specific packagenpm install package@latest# Update all patch versionsnpm update# Check for vulnerabilitiesnpm auditnpm audit fix
Common Issues:
- Peer dependency conflicts
- Incompatible version combinations
- Breaking changes during updates
- Node version compatibility
- Platform-specific issues
Performance Optimization Across Libraries
Bundle Size Reduction:
- Dynamic imports with Next.js
- Tree shaking with TypeScript
- Removing unused Tailwind classes
- Code splitting with React.lazy
- Analyzing with bundle-analyzer
Runtime Performance:
- React memo and callbacks
- Zustand selector optimization
- Redux reselect usage
- Lazy image loading with next/image
- Request deduplication with axios interceptors
Database Performance:
- Firestore query optimization
- Collection indexing
- Batch operations
- Caching strategies
When to Use This Skill
✅ Understanding how to set up each library properly ✅ Learning integration patterns between libraries ✅ Troubleshooting library-specific issues ✅ Optimizing performance with libraries ✅ Upgrading and managing dependencies ✅ Finding solutions to common pitfalls ✅ Learning best practices for each library ✅ Making choices between similar libraries (Zustand vs Redux) ✅ Quick reference for library syntax and APIs ✅ Deep diving into advanced usage
Quick Reference vs Deep Learning
This skill includes:
- ⚡ Quick lookup tables and syntax reference
- 📚 In-depth tutorials and explanations
- 🔧 Configuration file templates
- 🐛 Troubleshooting guides
- 🚀 Performance tips
- ⚠️ Common pitfalls and solutions
- 🔄 Integration patterns
- 📊 Comparison guides
- 💡 Real-world examples
- 🎯 Best practices
Resources & References
Quick Reference Guides
- next-js-quick-ref.md - Commands, config, routing
- react-hooks-reference.md - All hooks with examples
- typescript-quick-ref.md - Common patterns, syntax
- tailwind-utilities-ref.md - All utility classes
- firebase-methods-ref.md - All Firebase methods
- zod-validators-ref.md - All Zod validators
- stripe-api-ref.md - Stripe API methods
In-Depth Guides
- next-js-advanced.md - Advanced patterns, optimization
- react-performance.md - Rendering optimization
- typescript-advanced.md - Complex types, patterns
- tailwind-advanced.md - Custom plugins, design systems
- firebase-patterns.md - Architecture patterns
- zustand-vs-redux.md - Comparison and when to use
- form-validation-deep.md - Complex validation patterns
- stripe-complete.md - Full Stripe implementation
Troubleshooting & Common Issues
- common-errors.md - Error messages and solutions
- dependency-conflicts.md - Resolving version conflicts
- performance-issues.md - Identifying and fixing slowness
- type-errors.md - TypeScript error solutions
- build-issues.md - Next.js build troubleshooting
Integration Examples
- ecommerce-integration.md - Complete e-commerce setup
- saas-integration.md - SaaS platform setup
- authentication-flows.md - Auth integration patterns
- payment-integration.md - Payment processing setup
Technology Stack Details
Versions Covered:
- Next.js 13+
- React 18+
- TypeScript 4.5+
- Tailwind CSS 3+
- Firebase SDK (latest)
- Zustand 4+
- Redux Toolkit 1.9+
- react-hook-form 7+
- Zod 3+
- Stripe (latest)
Upgrade Paths:
- Next.js 12 → 13 → 14
- React 17 → 18
- Tailwind CSS 2 → 3
- TypeScript updates and breaking changes
- Firebase SDK v8 → v9 (modular SDK)
This comprehensive skill gives you complete mastery of the essential libraries and how they work together!