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

@usage-hooks/core

v1.1.0

Published

A collection of practical React hooks for real-world applications

Readme

@usage-hooks/core

A collection of practical React hooks for real-world applications

npm version License: MIT

Installation

npm install @usage-hooks/core

or

yarn add @usage-hooks/core

Features

  • 🎯 28 Production-Ready Hooks - Carefully selected for real-world use cases
  • 📘 TypeScript Support - Fully typed with comprehensive type definitions
  • 🎨 Tree-Shakeable - Import only what you need
  • SSR Compatible - Works with Next.js and other SSR frameworks
  • 📦 Lightweight - Minimal dependencies
  • Well Tested - Comprehensive test coverage
  • 🔄 Enhanced Features - Retry logic, caching, auto-reconnect, and more

Hooks

Storage Hooks

useLocalStorage

Persist state in localStorage with automatic serialization and cross-tab synchronization.

import { useLocalStorage } from 'usage-hooks';

function App() {
  const [name, setName] = useLocalStorage('username', 'Guest');
  
  return <input value={name} onChange={(e) => setName(e.target.value)} />;
}

useSessionStorage

Similar to useLocalStorage but uses sessionStorage.

const [token, setToken] = useSessionStorage('auth-token', null);

Performance Hooks

useDebounce

Debounce a value to limit update frequency.

import { useDebounce } from 'usage-hooks';

function SearchComponent() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearch = useDebounce(searchTerm, 500);
  
  useEffect(() => {
    // API call with debouncedSearch
    fetchResults(debouncedSearch);
  }, [debouncedSearch]);
}

useThrottle

Throttle a function to limit execution frequency.

const handleScroll = useThrottle(() => {
  console.log('Scrolling...');
}, 200);

Async Hooks

useAsync

Manage async operations with loading, error states, retry logic, and caching.

import { useAsync } from '@usage-hooks/core';

function UserProfile({ userId }) {
  const { execute, loading, data, error, retry } = useAsync(
    fetchUser,
    {
      retry: 3,
      retryDelay: 1000,
      cache: true,
      cacheKey: `user-${userId}`,
      onSuccess: (data) => console.log('User loaded:', data),
      onError: (error) => console.error('Failed:', error)
    }
  );
  
  useEffect(() => {
    execute(userId);
  }, [userId]);
  
  if (loading) return <div>Loading...</div>;
  if (error) return <button onClick={retry}>Retry</button>;
  return <div>{data?.name}</div>;
}

useFetch

Simplified data fetching with automatic request cancellation.

const { data, loading, error, refetch } = useFetch('/api/users');

useWebSocket

WebSocket connection management with auto-reconnect.

import { useWebSocket } from '@usage-hooks/core';

function ChatComponent() {
  const { sendMessage, lastMessage, isConnected, reconnect } = useWebSocket(
    'wss://echo.websocket.org',
    {
      onMessage: (event) => console.log('Received:', event.data),
      reconnect: true,
      reconnectInterval: 3000,
      reconnectAttempts: 5
    }
  );
  
  return (
    <div>
      <div>Status: {isConnected ? 'Connected' : 'Disconnected'}</div>
      <button onClick={() => sendMessage('Hello')}>Send</button>
      {!isConnected && <button onClick={reconnect}>Reconnect</button>}
    </div>
  );
}

State Management Hooks

useToggle

Manage boolean state with toggle function.

const [isOpen, toggleOpen, setIsOpen] = useToggle(false);

<button onClick={toggleOpen}>Toggle</button>

useForm

Form state management with validation.

const form = useForm({
  initialValues: { email: '', password: '' },
  validate: (values) => {
    const errors = {};
    if (!values.email) errors.email = 'Required';
    return errors;
  },
  onSubmit: async (values) => {
    await login(values);
  }
});

<form onSubmit={form.handleSubmit}>
  <input
    value={form.values.email}
    onChange={(e) => form.handleChange('email')(e.target.value)}
    onBlur={form.handleBlur('email')}
  />
  {form.errors.email && <span>{form.errors.email}</span>}
</form>

usePrevious

Track the previous value of a variable.

const [count, setCount] = useState(0);
const prevCount = usePrevious(count);

Lifecycle Hooks

useUpdateEffect

useEffect that skips the first render.

import { useUpdateEffect } from '@usage-hooks/core';

useUpdateEffect(() => {
  console.log('This runs on updates only, not on mount');
  fetchData();
}, [dependency]);

useMountEffect

Effect that runs only on component mount.

import { useMountEffect } from '@usage-hooks/core';

useMountEffect(() => {
  console.log('Component mounted');
  initializeApp();
});

useUnmountEffect

Effect that runs only on component unmount.

import { useUnmountEffect } from '@usage-hooks/core';

useUnmountEffect(() => {
  console.log('Component unmounting');
  cleanup();
});

UI Interaction Hooks

useClickOutside

Detect clicks outside of an element.

const ref = useClickOutside(() => {
  setIsOpen(false);
});

return <div ref={ref}>Modal content</div>;

useHover

Track element hover state.

const [ref, isHovered] = useHover();

return <div ref={ref}>{isHovered ? 'Hovering!' : 'Not hovering'}</div>;

useKeyPress

Detect specific key presses.

const enterPressed = useKeyPress('Enter');
const escapePressed = useKeyPress('Escape');

Browser API Hooks

useMediaQuery

Track CSS media query matches.

const isMobile = useMediaQuery('(max-width: 768px)');
const isDark = useMediaQuery('(prefers-color-scheme: dark)');

useWindowSize

Track window dimensions.

const { width, height } = useWindowSize();

useScrollPosition

Track scroll position.

const { x, y } = useScrollPosition();

useOnlineStatus

Detect network online/offline status.

const isOnline = useOnlineStatus();

useCopyToClipboard

Copy text to clipboard with feedback.

const [copiedText, copy] = useCopyToClipboard();

<button onClick={() => copy('Hello World')}>
  {copiedText ? 'Copied!' : 'Copy'}
</button>

useClipboard

Enhanced clipboard operations with read and write capabilities.

import { useClipboard } from '@usage-hooks/core';

function ClipboardDemo() {
  const { value, copy, read, isSupported } = useClipboard();
  
  if (!isSupported) {
    return <div>Clipboard API not supported</div>;
  }
  
  return (
    <div>
      <button onClick={() => copy('Hello World')}>Copy Text</button>
      <button onClick={read}>Read Clipboard</button>
      {value && <div>Clipboard content: {value}</div>}
    </div>
  );
}

useIntersectionObserver

Detect when element enters viewport (lazy loading, infinite scroll).

const [ref, isVisible] = useIntersectionObserver({
  threshold: 0.5,
  freezeOnceVisible: true
});

return <div ref={ref}>{isVisible ? 'Visible!' : 'Not visible'}</div>;

Timer Hooks

useInterval

Declarative interval that respects React lifecycle.

useInterval(() => {
  setCount(count + 1);
}, 1000);

useTimeout

Declarative timeout with automatic cleanup.

useTimeout(() => {
  console.log('Executed after 3 seconds');
}, 3000);

useIdle

Detect user idle state.

const isIdle = useIdle(5 * 60 * 1000); // 5 minutes

useEffect(() => {
  if (isIdle) {
    logout();
  }
}, [isIdle]);

Event Hooks

useEventListener

Add event listeners safely with automatic cleanup.

useEventListener('scroll', () => {
  console.log('Scrolling...');
});

TypeScript

All hooks are written in TypeScript and include comprehensive type definitions.

import { useLocalStorage, UseFormReturn } from 'usage-hooks';

interface LoginForm {
  email: string;
  password: string;
}

const form: UseFormReturn<LoginForm> = useForm({
  initialValues: { email: '', password: '' },
  onSubmit: async (values) => {
    // values is typed as LoginForm
  }
});

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT © [Your Name]

Support

If you find this library useful, please consider giving it a ⭐️ on GitHub!