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 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-nifty-hooks

v1.0.5

Published

React Custom Hooks

Downloads

80

Readme

React Nifty Hooks

React Nifty Hooks is a lightweight, efficient npm package that provides a collection of custom React hooks for common web development tasks, including form management, drag and drop, simplifying context api, outside click detection, local storage state management, window size monitoring, and data fetching with caching capabilities.

Installation

Install React Useful Hooks with npm:

npm install react-nifty-hooks

Or with yarn:

yarn add react-nifty-hooks

Table of Contents

| No. | Hooks | | --- | ------------------------------------------------------- | | | | | 1 | useForm | | 2 | useOutsideClick | | 3 | usePersistedState | | 4 | useDebounce | | 5 | useCurrentWindowSize | | 6 | useIntersectionObserver | | 7 | useInterval | | 8 | useMediaQuery | | 9 | usePrevious | | 10 | createTypeSafeContext | | 11 | useIntersectionObserver | | 12 | useDragAndDrop | | 13 | useFetchWithRetry | | 14 | useThrottle |

Usage

Below are examples on how to use each hook provided by this package.

useForm

Manage form states, handle changes, and validate form inputs with ease.

import { useForm } from 'react-nifty-hooks'

// Component example
const MyForm = () => {
  const { formInputs, onChangeHandler, onSubmitHandler, errors } = useForm(
    initialFormValues,
    handleSubmit,
    validateInputs
  )
  // Component logic...
}

useOutsideClick

Detect clicks outside of a specified element, useful for modals and dropdowns.

import { useOutsideClick } from 'react-nifty-hooks'

// Component example
const MyComponent = () => {
  const ref = useRef()
  const { activate, deactivate } = useOutsideClick(ref, () =>
    console.log('Clicked outside')
  )
  // Component logic...
}

usePersistedState

Persist state in localStorage for across-session state management.

import { usePersistedState } from 'react-nifty-hooks'

// Component example
const MyComponent = () => {
  const [value, setValue] = usePersistedState('myKey', initialValue)
  // Component logic...
}

useCurrentWindowSize

Monitor and respond to changes in the browser's window size.

import { useCurrentWindowSize } from 'react-nifty-hooks'

// Component example
const MyResponsiveComponent = () => {
  const { width, height } = useCurrentWindowSize()
  // Component logic...
}

useDataFetch

Fetch and cache data from an API, with built-in loading and error handling.

import { useDataFetch } from 'react-nifty-hooks'

// Component example
const MyDataFetcher = () => {
  const { data, isLoading, error, isError } = useDataFetch(url)
  // Component logic...
}

useDebounce

Delays the update of a value until after a specified duration, reducing the frequency of function calls.

Usage:

import { useDebounce } from 'react-nifty-hooks'

const SearchInput = ({ value }) => {
  const debouncedValue = useDebounce(value, 500)

  // Use debouncedValue for searching or other rate-limited actions
}

useIntersectionObserver

Observes an element's visibility within the viewport, perfect for lazy loading images or triggering animations on scroll.

Usage:

import { useRef } from 'react'
import { useIntersectionObserver } from 'react-nifty-hooks'

const LazyImage = src => {
  const imgRef = useRef()
  const isVisible = useIntersectionObserver(imgRef, { threshold: 0.1 })

  return <img ref={imgRef} src={isVisible ? src : 'placeholder.jpg'} alt='' />
}

useInterval

Facilitates the execution of a callback function at specified intervals. Ideal for creating timers, countdowns, or polling mechanisms.

Usage:

import { useInterval } from 'react-nifty-hooks'

const Timer = () => {
  useInterval(() => {
    // Callback code here
  }, 1000)
}

useMediaQuery

Enables components to adapt based on CSS media query matches, allowing for responsive design directly within your React components.

Usage:

import { useMediaQuery } from 'react-nifty-hooks'

const ResponsiveComponent = () => {
  const isMobile = useMediaQuery('(max-width: 768px)')

  return <div>{isMobile ? 'Mobile Content' : 'Desktop Content'}</div>
}

usePrevious

Stores and returns the previous value of a given variable or state, useful for comparisons or detecting changes.

Usage:

import { usePrevious } from 'react-nifty-hooks'

const CounterDisplay = ({ count }) => {
  const previousCount = usePrevious(count)

  return <div>Last count was {previousCount}</div>
}

createTypeSafeContext

Creates a type-safe context and a corresponding hook to access the context, ensuring the context is used within its Provider.

Usage:

// Defining the context
// UserProfileContext.ts
import { createTypeSafeContext } from 'react-nifty-hooks'

interface UserProfile {
  id: string
  name: string
  email: string
}

const defaultProfile: UserProfile = {
  id: '0',
  name: 'Guest',
  email: '[email protected]'
}

export const [useUserProfile, UserProfileProvider] =
  createTypeSafeContext<UserProfile>(defaultProfile)
// Providing the context
// App.tsx
import React from 'react'
import { UserProfileProvider } from './UserProfileContext'
import UserProfileComponent from './UserProfileComponent'

function App() {
  const user = {
    id: '123',
    name: 'John Doe',
    email: '[email protected]'
  }

  return (
    <UserProfileProvider value={user}>
      <div>
        <h1>Welcome to My App</h1>
        <UserProfileComponent />
      </div>
    </UserProfileProvider>
  )
}

export default App
// Consuming the context
// UserProfileComponent.tsx
import React from 'react'
import { useUserProfile } from './UserProfileContext'

function UserProfileComponent() {
  const userProfile = useUserProfile()

  return (
    <div>
      <h2>User Profile</h2>
      <p>Name: {userProfile.name}</p>
      <p>Email: {userProfile.email}</p>
    </div>
  )
}

export default UserProfileComponent

useDragAndDrop

The useDragAndDrop hook simplifies implementing drag-and-drop functionality. It manages the dragging state and the data being dragged, providing easy-to-use functions to handle drag start and end events.

import React from 'react'
import { useDragAndDrop } from 'react-nifty-hooks'

interface Item {
  id: number
  text: string
}

function DraggableItemComponent() {
  const { isDragging, draggedData, handleDragStart, handleDragEnd } =
    useDragAndDrop<Item>()

  return (
    <div>
      <div
        draggable
        onDragStart={() => handleDragStart({ id: 1, text: 'Drag me' })}
        onDragEnd={handleDragEnd}
        style={{ opacity: isDragging ? 0.5 : 1 }}
      >
        {isDragging ? 'Dragging...' : 'Drag me'}
      </div>
      {draggedData && <div>Dragging: {draggedData.text}</div>}
    </div>
  )
}

useFetchWithRetry

The useFetchWithRetryfetches data from a specified URL with retry logic, it attempts to make an HTTP GET request to retrieve data and will retry if the fetch fails.

import React from 'react'
import { useFetchWithRetry } from 'react-nifty-hooks'

const MyDataComponent = () => {
  const url = 'https://api.example.com/data' // The URL to fetch data from
  const options = {
    retries: 5, // Number of retry attempts
    retryDelay: 2000 // Delay between retries in milliseconds
  }

  const [data, loading, error] = useFetchWithRetry<MyDataType>(url, options)

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error! couldn't fetch datas</div>

  return (
    <div>
      <h1>Fetched Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

export default MyDataComponent

useThrottle

useThrottle hook throttles a function. The function will only be allowed to execute at most once every specified number of milliseconds.

import React, { useState } from 'react'
import useThrottle from './useThrottle'

const SearchComponent = () => {
  const [input, setInput] = useState('')
  const throttledInput = useThrottle(input, 1000) // Throttle input changes by 1 second

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInput(event.target.value)
  }

  // Imagine `searchAPI` is a function that triggers an API call
  useEffect(() => {
    if (throttledInput) {
      console.log('API call with:', throttledInput)
      // searchAPI(throttledInput);
    }
  }, [throttledInput])

  return (
    <div>
      <input type='text' value={input} onChange={handleChange} />
      <p>Throttled Value: {throttledInput}</p>
    </div>
  )
}

export default SearchComponent

Contributing

Contributions are always welcome! Please read the contribution guidelines first.

License

MIT © [Mahamudur Rahman Jewel]