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-custom-hooks-kit

v1.0.1

Published

React Custom Hooks with TypeScript offers essential, type-safe hooks crafted for smoother React development.

Downloads

35

Readme

react-custom-hooks-kit

npm version License Downloads GitHub stars GitHub forks GitHub issues GitHub pull requests Maintenance

Modern, type-safe React hooks library. Simplify your development with reusable hooks designed to enhance productivity. Explore the documentation for easy-to-use guides and examples.

Installation and Usage

Install:

npm install react-custom-hooks-kit

Table of Contents

| No. | Hooks | | --- | ------------------------------------------------------- | | | | | 1 | useFetch | | 2 | useLocalStorage | | 3 | useToggle | | 4 | useForm | | 5 | useScroll | | 6 | useMediaQuery | | 7 | useMousePosition | | 8 | useWindowSize | | 9 | useClickAway | | 10 | useCountDown | | 11 | useIntersectionObserver |

  1. useFetch

PARAMETERS

| Name | Type | Description | | ---- | ------ | ----------------------------------------- | | url | string | The URL from which data is to be fetched. |

RETURNS

| Name | Type | Description | | --------- | ------- | ------------------------------------------------------------- | | data | T[] | The response data fetched from the provided URL. | | error | object | Represents any error encountered during data fetching. | | isLoading | boolean | Loading State | | isError | boolean | Indicates whether an error occurred during the data fetching. |

Example Code:

import { useFetch } from 'react-custom-hooks-kit'

const Component = () => {
  const { data, isLoading, error, isError } = useFetch(
    'https://api.example.com/data'
  )

  if (isLoading) {
    return <div>Loading...</div>
  }

  if (isError) {
    return <div>Error occurred: {error?.message}</div>
  }

  return (
    <div>
      {data.map((item, index) => (
        <p key={index}>{item}</p>
      ))}
    </div>
  )
}
  1. useLocalStorage

useLocalStorage custom React hook that facilitates storing, retrieving, and synchronizing data with the browser's localStorage API.

PARAMETERS

| Name | Type | Description | | ------------ | ------ | ------------------------------------------------------------- | | key | string | The key under which the value will be stored in localStorage. | | initialValue | T | The initial value to be stored in localStorage. |

RETURNS

| Name | Type | Description | | ------------- | -------- | ---------------------------------------------------------------- | | savedValue | T | The current state of the value stored in local storage. | | setSavedValue | function | A function to set the state of the stored value in localStorage. |

Example Code:

import { useLocalStorage } from 'react-custom-hooks-kit'

const Component = () => {
  const [savedValue, setSavedValue] = useLocalStorage('myKey', 'defaultValue')

  const handleInputChange = e => {
    setSavedValue(e.target.value)
  }

  return (
    <div>
      <input type='text' value={savedValue} onChange={handleInputChange} />
    </div>
  )
}
  1. useToggle

PARAMETERS

| Name | Type | Description | | ------------ | ------- | ------------------------------------------------------------------------------------------------------------- | | initialValue | boolean | Default value set to false. Change this parameter to the desired boolean value if different from the default. |

RETURNS

| Name | Type | Description | | -------- | -------- | ---------------------------------- | | isOn | boolean | Current state | | onToggle | function | Function to toggle between states. |

Example Code:

import { useToggle } from 'react-custom-hooks-kit'

const ToggleButton = () => {
  const [isOn, toggle] = useToggle(false)

  return (
    <div>
      <button onClick={toggle}>{isOn ? 'ON' : 'OFF'}</button>
      <p>Toggle state: {isOn ? 'ON' : 'OFF'}</p>
    </div>
  )
}
  1. useForm

PARAMETERS

| Name | Type | Description | | ----------------- | ------------------ | --------------------------------------------------------------------------------------------------------- | | initialInputValue | object | initial state. | | submitCallback | function | Callback function that receives the form input value for further processing or backend interaction. | | inputValidator | validator function | Callback function to validate each input field and return an object containing validation error messages. |

RETURNS

| Name | Type | Description | | --------------- | -------- | --------------------------------------------------------------------------------------------------------- | | onChangeHandler | function | Function to handle input changes within the form. | | onSubmitHandler | function | Function to handle form submissions. | | formInputs | object | Object containing form input values that correspond to their respective field names. | | errors | object | Object containing validation error messages corresponding to the fields validated through inputValidator. |

Example Code:

import { useForm } from 'react-custom-hooks-kit'

const initialState = {
  email: '',
  password: ''
}

const validator = inputValue => {
  const error = {}
  if (inputValue.password && inputValue.password.length < 6) {
    error.password = 'Password should be more than 6 characters.'
  }
  // ... add other validations
  return error
}

const Form = () => {
  const sendFormData = inputValue => {
    console.log(inputValue)
    // ... process data further
  }

  const { onChangeHandler, onSubmitHandler, formInputs, errors } = useForm(
    initialState,
    sendFormData,
    validator
  )

  return (
    <form onSubmit={onSubmitHandler}>
      <input
        value={formInputs.email}
        type='email'
        name='email'
        onChange={onChangeHandler}
      />
      <input
        value={formInputs.password}
        type='password'
        name='password'
        onChange={onChangeHandler}
      />
      <button type='submit'>Submit</button>
    </form>
  )
}
  1. useScroll

RETURNS

| Name | Type | Description | | --------------- | ------ | ----------------------- | | currentPosition | number | Current scroll position |

Example Code:

import { useScroll } from 'react-custom-hooks-kit'

const Component = () => {
  const { currentPosition } = useScroll()

  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <h2 style={{ position: 'fixed', top: '0', left: '0' }}>
        Current Scroll: {currentPosition}
      </h2>
    </div>
  )
}
  1. useMediaQuery

PARAMETERS

| Name | Type | Description | | ----- | ------ | -------------------------------------------------------------------------- | | query | string | A string representing the media query to be tested. Ex: 'max-width: 768px' |

RETURNS

| Name | Type | Description | | ------- | ------- | ---------------------------------------------------------- | | matches | boolean | Represents whether the current viewport matches the query. |

Example Code:

import { useMediaQuery } from 'react-custom-hooks-kit'

const Component = () => {
  const isMobile = useMediaQuery('(max-width: 568px)')
  const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)')
  const isDesktop = useMediaQuery('(min-width: 1025px)')

  return (
    <div>
      <p>Is Mobile? {isMobile ? 'Yes' : 'No'}</p>
      <p>Is Tablet? {isTablet ? 'Yes' : 'No'}</p>
      <p>Is Desktop? {isDesktop ? 'Yes' : 'No'}</p>
    </div>
  )
}
  1. useMousePosition

PARAMETERS

| Name | Type | Description | | ---- | ----------------------------- | ------------------------------------- | | ref | MutableRefObject | Reference to the target HTML element. |

RETURNS

| Name | Type | Description | | -------------------- | ---------------------------------------------- | ------------------------------------------------------------- | | currentMousePosition | MousePosition object: { x: number, y: number } | Represents the current mouse coordinates (x and y positions). |

Example Code:

import { useMousePosition } from 'react-custom-hooks-kit'
import { useRef } from 'react'

const Component = () => {
  const elementRef = useRef(null)
  const mouse = useMousePosition(elementRef)

  return (
    <section
      ref={elementRef}
      style={{ width: '100%', height: '400px', backgroundColor: 'lightgray' }}
    >
      <p>
        X: {mouse.x}, Y: {mouse.y}
      </p>
    </section>
  )
}
  1. useWindowSize

RETURNS

| Name | Type | Description | | ------ | ------ | ---------------------------------------------------- | | width | number | Represents the current width of the browser window. | | height | number | Represents the current height of the browser window. |

Example Code:

import { useWindowSize } from 'react-custom-hooks-kit'

const WindowSizeComponent = () => {
  const { width, height } = useWindowSize()

  return (
    <div>
      <p>Window Width: {width}px</p>
      <p>Window Height: {height}px</p>
    </div>
  )
}
  1. useClickAway

PARAMETERS

| Name | Type | Description | | ----------- | ---------------- | ------------------------------------------------------------------------- | | ref | MutableRefObject | Reference to the target HTML element. | | onClickAway | function | Callback function triggered when a click is detected outside the element. |

RETURNS

| Name | Type | Description | | ------- | -------- | --------------------------------- | | enable | function | Enables the click-away listener. | | disable | function | Disables the click-away listener. |

Example Code:

import { useClickAway } from 'react-custom-hooks-kit'

const Component = () => {
  const clickRef = useRef(null)
  const [isOpen, setIsOpen] = useState(false)

  const handleClickAway = () => {
    setIsOpen(false)
  }
  const { enable, disable } = useClickAway(clickRef, handleClickAway)

  return (
    <section ref={clickRef}>
      <button onClick={() => setIsOpen(true)}>Open Modal</button>
      {isOpen && (
        <div>
          <div>
            <button onClick={enable}>Enable</button>
            <button onClick={disable}>Disable</button>
          </div>
          <h2>Modal</h2>
        </div>
      )}
    </section>
  )
}
  1. useCountDown

PARAMETERS

| Name | Type | Description | | ----- | ------ | -------------------------------------------------- | | count | number | The initial count value for the countdown. | | delay | number | The delay (in milliseconds) between count updates. |

RETURNS

| Name | Type | Description | | ------------ | ------ | ---------------------------------------------------- | | currentCount | number | Represents the current count value of the countdown. |

Example Code:

import { useCountDown } from 'react-custom-hooks-kit'

const Component = () => {
  const countDown = useCountDown(10, 200) // Start countdown from 10 with a delay of 200 ms.

  return (
    <div>
      <p>Countdown: {countDown}</p>
    </div>
  )
}
  1. useIntersectionObserver

useIntersectionObserver custom Hook that determines if a component is visible on your screen. It relies on the IntersectionObserver API, which is already available in your browser. This hook comes in handy for tasks such as loading images when they come into view, creating endless scrolling on pages, or triggering animations.

PARAMETERS

| Name | Type | Description | | ----------------------- | ---------------------------- | --------------------------------------------------------------- | | ref | MutableRefObject | Reference to the observed HTML element. | | options | object | Intersection Observer configuration options. | | options.threshold | number (*default 0.3) | The ratio of intersection needed to trigger the callback. | | options.root | HTMLElement (*default null) | The element used as the viewport for checking intersection. | | options.rootMargin | string (*default "0%") | Margin around the root element to adjust the intersection area. | | options.stopOnceVisible | boolean (*default false) | Stops observing once the element becomes visible. |

RETURNS

| Name | Type | Description | | ----------------- | --------------------------------- | ------------------------------------------------------------ | | intersectionEntry | IntersectionObserverEntry | null | Represents the intersection details of the observed element. |

Example Code:


import { useIntersectionObserver } from react-custom-hooks-kit';
import React, { useRef } from 'react';

const IntersectionComponent = () => {
  const targetRef = useRef(null);
  const intersectionEntry = useIntersectionObserver(targetRef, {
    threshold: 0.5,
    root: null,
    rootMargin: '0%',
    stopOnceVisible: true
  });

  const isVisible = intersectionEntry?.isIntersecting;

  return (
    <div>
      <div
        ref={targetRef}
        style={{
          height: '200px',
          backgroundColor: isVisible ? 'yellow' : 'gray'
        }}
      >
        {isVisible ? 'Element visible!' : 'Scroll to see me!'}
      </div>
    </div>
  );
};


const Component = () => {
  return (
    <main>
      {Array.from({ length: 5 }).map((_, index) => (
        <IntersectionComponent key={index + 1} />
      ))}
    </main>
  )
}

⬆ Back to Top