npm package: @rodrigo0000/core-hooks
Description: A comprehensive collection of React hooks for SaaS applications
Author: Rodrigo
Latest version: 1.0.2

# Core Hooks Library

A comprehensive collection of React hooks designed for SaaS applications. This library provides production-ready hooks for authentication, API management, data handling, and system utilities.

## Installation

```bash
# If this were published to npm
npm install @components-factory/core-hooks
```

## Quick Start

```typescript
import { useAuth, useFetch, useDebounce, useOnlineStatus } from '@components-factory/core-hooks';

function MyComponent() {
  const { user, isAuthenticated } = useAuth();
  const { data, isLoading } = useFetch('/api/users');
  const debouncedValue = useDebounce(searchTerm, { delay: 300 });
  const { isOnline } = useOnlineStatus();
  
  return (
    <div>
      {isAuthenticated ? `Welcome ${user?.name}` : 'Please login'}
      {isOnline ? 'Connected' : 'Offline'}
    </div>
  );
}
```

## Hook Categories

### 🔐 Authentication Hooks

- **`useAuth`** - Complete authentication state management
- **`useLogin`** - Login functionality with error handling
- **`useLogout`** - Logout functionality with cleanup

### 🌐 API Hooks

- **`useFetch`** - Data fetching with caching and retry logic
- **`useMutation`** - API mutations with optimistic updates
- **`usePaginatedQuery`** - Paginated data fetching

### 📊 Data Management Hooks

- **`useDebounce`** - Value debouncing with advanced controls
- **`useLocalStorage`** - Local storage with cross-tab sync
- **`useWindowSize`** - Window size tracking with breakpoints

### ⚙️ System Utility Hooks

- **`useKeyboardShortcut`** - Keyboard shortcut management
- **`useMounted`** - Component mount state tracking
- **`useOnlineStatus`** - Network connectivity detection

## Features

### 🚀 Production Ready
- Comprehensive error handling
- Memory leak prevention
- SSR compatibility
- TypeScript support

### 🔧 Advanced Functionality
- Service classes for complex state management
- Event-driven architecture
- Configurable options
- Utility functions

### 📱 SaaS Optimized
- Authentication flows
- API state management
- Offline-first patterns
- User experience enhancements

## Usage Examples

### Authentication Flow

```typescript
import { useAuth, useLogin, useLogout } from '@components-factory/core-hooks';

function AuthComponent() {
  const { user, isAuthenticated, isLoading } = useAuth();
  const { login, isLoading: isLoggingIn } = useLogin({
    onSuccess: (user, token) => {
      console.log('Login successful:', user);
    }
  });
  const { logout } = useLogout();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      {isAuthenticated ? (
        <div>
          <p>Welcome, {user?.name}!</p>
          <button onClick={() => logout()}>Logout</button>
        </div>
      ) : (
        <button 
          onClick={() => login({ email: 'user@example.com', password: 'password' })}
          disabled={isLoggingIn}
        >
          {isLoggingIn ? 'Logging in...' : 'Login'}
        </button>
      )}
    </div>
  );
}
```

### Data Fetching with Caching

```typescript
import { useFetch, useMutation } from '@components-factory/core-hooks';

function UserList() {
  const { data: users, isLoading, error, refetch } = useFetch('/api/users', {
    staleTime: 5 * 60 * 1000, // 5 minutes
    cacheTime: 10 * 60 * 1000, // 10 minutes
  });

  const { mutate: createUser, isLoading: isCreating } = useMutation('/api/users', {
    method: 'POST',
    onSuccess: () => {
      refetch(); // Refresh the list
    }
  });

  if (isLoading) return <div>Loading users...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <button 
        onClick={() => createUser({ name: 'New User', email: 'new@example.com' })}
        disabled={isCreating}
      >
        {isCreating ? 'Creating...' : 'Add User'}
      </button>
      <ul>
        {users?.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}
```

### Debounced Search

```typescript
import { useDebounce, useFetch } from '@components-factory/core-hooks';
import { useState } from 'react';

function SearchComponent() {
  const [searchTerm, setSearchTerm] = useState('');
  const { debouncedValue, isDebouncing } = useDebounce(searchTerm, { 
    delay: 300,
    leading: false,
    trailing: true 
  });

  const { data: results, isLoading } = useFetch(
    debouncedValue ? `/api/search?q=${debouncedValue}` : null
  );

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        placeholder="Search..."
      />
      {(isDebouncing || isLoading) && <span>Searching...</span>}
      {results && (
        <ul>
          {results.map(item => (
            <li key={item.id}>{item.title}</li>
          ))}
        </ul>
      )}
    </div>
  );
}
```

### Keyboard Shortcuts

```typescript
import { useKeyboardShortcut, useEscapeKey } from '@components-factory/core-hooks';

function ShortcutComponent() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  useKeyboardShortcut('ctrl+k', () => {
    setIsModalOpen(true);
  }, {
    description: 'Open search modal'
  });

  useEscapeKey(() => {
    setIsModalOpen(false);
  }, {
    enabled: isModalOpen
  });

  return (
    <div>
      <p>Press Ctrl+K to open modal, Esc to close</p>
      {isModalOpen && (
        <div className="modal">
          <p>Modal is open!</p>
        </div>
      )}
    </div>
  );
}
```

### Responsive Design

```typescript
import { useWindowSize, useBreakpoint } from '@components-factory/core-hooks';

function ResponsiveComponent() {
  const { width, height, isLandscape, breakpoint } = useWindowSize();
  const currentBreakpoint = useBreakpoint();

  return (
    <div>
      <p>Window: {width}x{height}</p>
      <p>Orientation: {isLandscape ? 'Landscape' : 'Portrait'}</p>
      <p>Breakpoint: {breakpoint}</p>
      {currentBreakpoint === 'sm' && <p>Mobile view</p>}
      {currentBreakpoint === 'lg' && <p>Desktop view</p>}
    </div>
  );
}
```

### Network Status

```typescript
import { useOnlineStatus, useOfflineFirst } from '@components-factory/core-hooks';

function NetworkComponent() {
  const { isOnline, isChecking, forceCheck } = useOnlineStatus({
    pingInterval: 30000, // Check every 30 seconds
    onOffline: () => console.log('Gone offline'),
    onOnline: () => console.log('Back online')
  });

  const { data, isLoading, error, retry } = useOfflineFirst(
    // Online callback
    () => fetch('/api/data').then(res => res.json()),
    // Offline callback
    () => JSON.parse(localStorage.getItem('cachedData') || '{}')
  );

  return (
    <div>
      <div className={`status ${isOnline ? 'online' : 'offline'}`}>
        {isOnline ? '🟢 Online' : '🔴 Offline'}
        {isChecking && ' (checking...)'}
      </div>
      <button onClick={forceCheck}>Check Connection</button>
      {error && <button onClick={retry}>Retry</button>}
    </div>
  );
}
```

## Advanced Usage

### Service Classes

Each hook comes with a corresponding service class for advanced use cases:

```typescript
import { AuthService, DebounceService, WindowSizeService } from '@components-factory/core-hooks';

// Create services outside of React components
const authService = new AuthService({
  apiBaseUrl: 'https://api.example.com',
  autoRefresh: true
});

const debounceService = new DebounceService('initial value', {
  delay: 500,
  maxWait: 2000
});

// Use in vanilla JavaScript or other frameworks
authService.on('login', (data) => {
  console.log('User logged in:', data);
});

debounceService.subscribe((state) => {
  console.log('Debounced value:', state.debouncedValue);
});
```

### Utility Functions

```typescript
import { 
  getAuthToken, 
  setAuthToken, 
  isAuthenticated,
  getLocalStorageItem,
  setLocalStorageItem,
  isOnline,
  waitForOnline 
} from '@components-factory/core-hooks';

// Direct utility usage
const token = getAuthToken();
const userData = getLocalStorageItem('user', {});
const connectionStatus = isOnline();

// Async utilities
await waitForOnline(10000); // Wait up to 10 seconds for connection
```

## Configuration

### Global Configuration

```typescript
import { createAuthService, createOnlineStatusService } from '@components-factory/core-hooks';

// Configure auth service globally
const authService = createAuthService({
  apiBaseUrl: process.env.REACT_APP_API_URL,
  tokenKey: 'my_app_token',
  autoRefresh: true,
  refreshThreshold: 5 // minutes
});

// Configure network monitoring
const networkService = createOnlineStatusService({
  pingUrl: 'https://my-api.com/health',
  pingInterval: 60000, // 1 minute
  pingTimeout: 5000
});
```

### Environment Variables

```env
REACT_APP_API_URL=https://api.example.com
VITE_API_BASE_URL=https://api.example.com
```

## TypeScript Support

All hooks are fully typed with comprehensive TypeScript definitions:

```typescript
import type { 
  User, 
  AuthState, 
  FetchResult, 
  WindowSizeResult,
  OnlineStatusResult 
} from '@components-factory/core-hooks';

interface MyUser extends User {
  role: 'admin' | 'user';
  permissions: string[];
}

const { user } = useAuth<MyUser>();
const { data } = useFetch<MyUser[]>('/api/users');
```

## Best Practices

### 1. Error Handling

```typescript
const { data, error, isError } = useFetch('/api/data', {
  onError: (error) => {
    // Log to error reporting service
    console.error('API Error:', error);
  }
});

if (isError) {
  return <ErrorComponent error={error} />;
}
```

### 2. Performance Optimization

```typescript
// Use debouncing for expensive operations
const debouncedSearch = useDebounce(searchTerm, { delay: 300 });

// Cache API responses
const { data } = useFetch('/api/data', {
  staleTime: 5 * 60 * 1000, // 5 minutes
  cacheTime: 10 * 60 * 1000 // 10 minutes
});

// Optimize window size tracking
const { breakpoint } = useWindowSize({ 
  debounceMs: 100,
  enableHighFrequency: false 
});
```

### 3. Memory Management

```typescript
// Hooks automatically clean up, but you can also manually control
const { cancel: cancelDebounce } = useDebounce(value);
const { removeValue } = useLocalStorage('key', defaultValue);

// Use safe async operations
const { safeAsync } = useSafeAsync();

useEffect(() => {
  safeAsync(async () => {
    const data = await fetchData();
    // This won't execute if component unmounted
    setData(data);
  });
}, []);
```

## Browser Support

- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+

## Contributing

This library is part of the ComponentsFactory project. Each hook is designed to be:

- **Reusable** across different SaaS applications
- **Type-safe** with comprehensive TypeScript support
- **Performant** with proper cleanup and optimization
- **Testable** with clear separation of concerns

## License

MIT License - see LICENSE file for details.