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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@rodrigo0000/core-hooks

v1.0.2

Published

A comprehensive collection of React hooks for SaaS applications

Readme

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

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

Quick Start

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

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: '[email protected]', password: 'password' })}
          disabled={isLoggingIn}
        >
          {isLoggingIn ? 'Logging in...' : 'Login'}
        </button>
      )}
    </div>
  );
}

Data Fetching with Caching

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: '[email protected]' })}
        disabled={isCreating}
      >
        {isCreating ? 'Creating...' : 'Add User'}
      </button>
      <ul>
        {users?.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Debounced Search

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

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

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

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:

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

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

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

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:

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

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

// 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

// 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.