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

hooks-belt

v1.0.11

Published

A comprehensive collection of useful React hooks for common use cases

Readme

Hooks Belt 🎯

A comprehensive collection of useful React hooks for common use cases. Built with TypeScript and designed for production use.

✨ Features

  • 11 Custom Hooks - Covering the most common React development needs
  • Full TypeScript Support - Complete type definitions and IntelliSense
  • Production Ready - Well-tested and optimized for real-world usage
  • Zero Dependencies - Only requires React as a peer dependency
  • Tree Shakeable - Import only the hooks you need

📦 Installation

npm install hooks-belt

or

yarn add hooks-belt

🚀 Quick Start

import { useDebounce, useLocalStorage, useToggle, useDownloadFile } from 'hooks-belt'

function MyComponent() {
  const [searchTerm, setSearchTerm] = useState('')
  const debouncedSearchTerm = useDebounce(searchTerm, 300)
  
  const [user, setUser] = useLocalStorage('user', { name: 'John' })
  const [isOpen, toggle] = useToggle(false)
  
  const { downloadFile, isLoading } = useDownloadFile()
  
  // Your component logic here
}

📚 Available Hooks

useDebounce

Delays the execution of a function or value update. Perfect for search inputs and API calls.

const [searchTerm, setSearchTerm] = useState('')
const debouncedSearchTerm = useDebounce(searchTerm, 500)

useEffect(() => {
  // This will only run after the user stops typing for 500ms
  searchAPI(debouncedSearchTerm)
}, [debouncedSearchTerm])

useThrottle

Limits the rate at which a function can be executed. Great for scroll handlers and resize events.

const throttledScrollHandler = useThrottle(() => {
  console.log('Scroll event throttled')
}, 100)

useEffect(() => {
  window.addEventListener('scroll', throttledScrollHandler)
  return () => window.removeEventListener('scroll', throttledScrollHandler)
}, [throttledScrollHandler])

useLocalStorage

Provides a way to persist state in localStorage with automatic JSON serialization.

const [user, setUser] = useLocalStorage('user', { name: 'John', age: 30 })

// Update the user
setUser({ name: 'Jane', age: 25 })

// The value is automatically saved to localStorage

useMediaQuery

Responds to media queries and automatically updates when the query matches or doesn't match.

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

return (
  <div className={isMobile ? 'mobile-layout' : 'desktop-layout'}>
    {isDarkMode ? 'Dark mode' : 'Light mode'}
  </div>
)

usePrevious

Returns the previous value of a state or prop. Useful for comparing current and previous values.

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

useEffect(() => {
  if (previousCount !== undefined && count > previousCount) {
    console.log('Count increased!')
  }
}, [count, previousCount])

useToggle

Provides a boolean state with toggle functionality and additional setter functions.

const [isOpen, toggle, setOpen, setClosed] = useToggle(false)

return (
  <div>
    <button onClick={toggle}>Toggle</button>
    <button onClick={setOpen}>Open</button>
    <button onClick={setClosed}>Close</button>
    {isOpen && <Modal />}
  </div>
)

useOnClickOutside

Detects clicks outside of a specified element. Perfect for modals and dropdowns.

const modalRef = useRef<HTMLDivElement>(null)
const [isOpen, setIsOpen] = useState(false)

useOnClickOutside(modalRef, () => setIsOpen(false))

return (
  {isOpen && (
    <div ref={modalRef} className="modal">
      Modal content
    </div>
  )}
)

useFetch

Provides a way to fetch data with loading and error states.

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

if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>

return (
  <div>
    {data?.map(user => <User key={user.id} user={user} />)}
    <button onClick={refetch}>Refresh</button>
  </div>
)

useWindowSize

Tracks the window dimensions and automatically updates when the window is resized.

const { width, height } = useWindowSize()

return (
  <div>
    Window size: {width} x {height}
    {width < 768 && <MobileMenu />}
  </div>
)

useInterval

Provides a way to run a function at regular intervals with pause/resume functionality.

const [count, setCount] = useState(0)
const [isRunning, setIsRunning] = useState(true)

useInterval(
  () => setCount(c => c + 1),
  isRunning ? 1000 : null
)

return (
  <div>
    Count: {count}
    <button onClick={() => setIsRunning(!isRunning)}>
      {isRunning ? 'Pause' : 'Resume'}
    </button>
  </div>
)

useDownloadFile

Provides file download functionality with loading state management and automatic cleanup.

const { downloadFile, isLoading } = useDownloadFile()

const handleDownload = async () => {
  const response = await fetch('/api/file')
  const blob = await response.blob()
  await downloadFile({ 
    data: blob, 
    fileName: 'document.pdf' 
  })
}

return (
  <button onClick={handleDownload} disabled={isLoading}>
    {isLoading ? 'Downloading...' : 'Download File'}
  </button>
)

🧪 Testing

Run the test suite:

npm test

Run tests in watch mode:

npm run test:watch

Generate coverage report:

npm run test:coverage

🏗️ Development

Prerequisites

  • Node.js 18+
  • npm or yarn

Setup

  1. Clone the repository:
git clone https://github.com/morozander/hooks-belt.git
cd hooks-belt
  1. Install dependencies:
npm install
  1. Start development server:
npm run dev
  1. Build the library:
npm run build:lib

Project Structure

hooks-belt/
├── src/
│   ├── hooks/           # Individual hook implementations
│   ├── test/            # Test setup and utilities
│   ├── App.tsx          # Demo application
│   └── index.ts         # Main export file
├── dist/                # Built library files
├── tests/               # Unit tests for each hook
├── package.json         # Package configuration
├── tsconfig.json        # TypeScript configuration
├── vitest.config.ts     # Test configuration
└── README.md            # This file

🤝 Contributing

We welcome contributions! Here's how you can help:

Reporting Issues

  • Use the GitHub issue tracker
  • Include a clear description of the problem
  • Provide steps to reproduce the issue
  • Include your environment details

Submitting Pull Requests

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass: npm test
  6. Commit your changes: git commit -m 'Add amazing feature'
  7. Push to the branch: git push origin feature/amazing-feature
  8. Open a Pull Request

Code Style

  • Follow the existing TypeScript/React patterns
  • Include JSDoc comments for all public APIs
  • Write comprehensive tests for new hooks
  • Ensure your code passes linting: npm run lint

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Inspired by the React community's need for reusable hooks
  • Built with modern tooling (Vite, TypeScript, Vitest)
  • Thanks to all contributors and users

Made with ❤️ for the React community