1.0.0 โ€ข Published 5 months ago

react-hookman v1.0.0

Weekly downloads
-
License
-
Repository
github
Last release
5 months ago

React hookman Logo

Generated by AI

React Hookman

A collection of reusable and type-safe React hooks to simplify your development workflow.

Installation

npm install react-hookman

or

yarn add react-hookman

Available Hooks

useBoolean

useClickOutside

useClipboard

useDebounce

useDestroy

useDragNDrop

useFetch

useHover

useMousePosition

useIdle

useLongPress

useMobile

useMousePosition

useOnlineStatus

usePageTitle

useScrollPosition

useToggle

useTruncate

useUpdateEffect

useWindowSize


๐Ÿ”„ useBoolean ๐ŸŽ›๏ธ

A hook for managing boolean state with utility functions.

Parameters

  • initialValue: boolean (optional) โ€“ Initial state, defaults to false

Returns

  • value: Current boolean state
  • setValue(value: boolean): Sets the state to a specific value
  • setTrue(): Sets the state to true
  • setFalse(): Sets the state to false
  • toggle(): Toggles the current state

๐Ÿ”ง Usage

const { value, setTrue, setFalse, toggle } = useBoolean(false);
return (
  <div style={{ padding: "20px" }}>
    <h2>useBoolean Hook Demo</h2>

    <div style={{ marginBottom: "20px" }}>
      <p>Current value: {value.toString()}</p>
    </div>

    <div style={{ display: "flex", gap: "10px" }}>
      <button onClick={toggle}>Toggle</button>
      <button onClick={setTrue}>Set True</button>
      <button onClick={setFalse}>Set False</button>
    </div>

    {value && (
      <div
        style={{
          marginTop: "20px",
          padding: "20px",
          backgroundColor: "#e0e0e0",
        }}
      >
        This content is visible when value is true!
      </div>
    )}
  </div>
);

๐ŸŽฏ useClickOutside ๐Ÿ–ฑ๏ธ

React hook that detects clicks outside a specified element and triggers a callback.

Parameters

  • ref: RefObject<T> - Reference to the target HTML element
  • cb: () => void - Callback function triggered on outside clicks

Returns

  • void

Type Parameters

  • T extends HTMLElement - Type of the referenced HTML element

Notes

  • Automatically cleans up event listeners on unmount
  • Attaches to mousedown event on document
  • Safe to use with null refs

๐Ÿ”ง Usage

const Modal: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const modalRef = useRef<HTMLDivElement | null>(null);

  useClickOutside(modalRef as React.RefObject<HTMLElement>, () =>
    setIsOpen(false)
  );

  return (
    <div>
      <button onClick={() => setIsOpen(true)}>Open Modal</button>

      {isOpen && (
        <div
          style={{
            position: "fixed",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            padding: "20px",
            background: "white",
            boxShadow: "0px 4px 10px rgba(0,0,0,0.1)",
            borderRadius: "8px",
          }}
          ref={modalRef}
        >
          <p>This is a modal. Click outside to close.</p>
        </div>
      )}
    </div>
  );
};

๐Ÿ“‹ useClipboard Hook

A React hook for copying text to the clipboard with both Clipboard API and fallback support. It also provides a copied state to track copy status.


Returns

  • copied: boolean - Indicates if text was recently copied
  • copyToClipboard(text: string): Promise<void> - Copies text to clipboard

Features

  • Uses modern Clipboard API with fallback
  • Auto-resets copy status after 2 seconds
  • Handles errors gracefully
  • Works in all modern browsers

Notes

  • Copy status resets automatically after 2000ms
  • Falls back to execCommand if Clipboard API unavailable
  • Logs errors to console if copy fails

๐Ÿ”ง Usage

import React, { useState } from "react";
import { useClipboard } from "./useClipboard";

const ClipboardExample: React.FC = () => {
  const { copied, copyToClipboard } = useClipboard();
  const [text, setText] = useState("Hello, World!");

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Enter text to copy"
      />
      <button onClick={() => copyToClipboard(text)}>
        {copied ? "Copied!" : "Copy to Clipboard"}
      </button>
    </div>
  );
};

export default ClipboardExample;

โณ useDebounce Hook

A React hook for debouncing values. It delays updating the state until after a specified time has passed since the last change.


๐Ÿ”ง Usage

import React, { useState } from "react";
import { useDebounce } from "./useDebounce";

const DebounceExample: React.FC = () => {
  const [text, setText] = useState("");
  const debouncedText = useDebounce(text, 500);

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something..."
      />
      <p>Debounced Value: {debouncedText}</p>
    </div>
  );
};

export default DebounceExample;

๐Ÿ›  API

useDebounce<T>(value: T, delay?: number): T

Returns the debounced value after the specified delay.

ParameterTypeDefaultDescription
valueTโ€”The value to debounce.
delaynumber500The debounce delay in milliseconds (optional).

๐Ÿ›‘ useDestroy Hook

A React hook that runs a cleanup function when a component unmounts. Useful for handling cleanup logic like removing event listeners, aborting requests, or clearing intervals.


๐Ÿ”ง Usage

import React, { useState } from "react";
import { useDestroy } from "./useDestroy";

const DestroyExample: React.FC = () => {
  const [visible, setVisible] = useState(true);

  return (
    <div>
      <button onClick={() => setVisible(!visible)}>
        {visible ? "Unmount Component" : "Mount Component"}
      </button>
      {visible && <ChildComponent />}
    </div>
  );
};

const ChildComponent: React.FC = () => {
  useDestroy(() => {
    console.log("Component unmounted! Cleanup logic here.");
  });

  return <p>This component will trigger cleanup on unmount.</p>;
};

export default DestroyExample;

๐Ÿ›  API

useDestroy(func: () => void)

Runs the provided function when the component unmounts.

ParameterTypeDescription
func() => voidThe function to execute when the component unmounts

๐Ÿ”„ useDragAndDrop ๐Ÿ–ฑ๏ธ

React hook for adding drag and drop functionality to elements.

Usage

 function App() {
  const [ref, isDragging] = useDragAndDrop<HTMLDivElement>(); // Explicitly type the ref

  return (
    <div
      ref={ref}
  style={{
    position: "absolute",
      backgroundColor: "lightblue",
      padding: "10px",
      cursor: isDragging ? "grabbing" : "grab",
  }}
>
  Drag me!
  </div>
);

Returns

  • elementRef: RefObject<T> - Reference to attach to draggable element
  • isDragging: boolean - Current drag state

Type Parameters

  • T extends HTMLElement - Type of the draggable element

Notes

  • Element must have position: absolute style
  • Handles mouse events automatically
  • Cleans up event listeners on unmount
  • Updates element position in real-time
  • Tracks offset from click position

๐ŸŒ useFetch Hook

A custom React hook for fetching data asynchronously with built-in support for loading state, error handling, retries, and aborting requests.


๐Ÿš€ Installation

This is a standalone hook. You can directly copy and use it in your React project.


๐Ÿ”ง Usage

import React, { useState } from "react";
import { useFetch } from "./useFetch";

const FetchExample: React.FC = () => {
  const [url, setUrl] = useState(
    "https://jsonplaceholder.typicode.com/posts/1"
  );

  const { data, loading, error, retry } = useFetch<{
    title: string;
    body: string;
  }>(url);

  return (
    <div>
      <h2>Fetch Example</h2>
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {data && (
        <div>
          <h3>{data.title}</h3>
          <p>{data.body}</p>
        </div>
      )}
      <button onClick={retry}>Retry</button>
      <button
        onClick={() => setUrl("https://jsonplaceholder.typicode.com/posts/2")}
      >
        Fetch Another Post
      </button>
    </div>
  );
};

export default FetchExample;

๐Ÿ›  API

useFetch<T>(url: string, options?: FetchOptions): UseFetchReturn<T>

Parameters

ParameterTypeDescription
urlstringThe API endpoint to fetch data from
optionsFetchOptionsFetch configuration (headers, method, body, etc.)

FetchOptions (Extends RequestInit)

OptionTypeDefaultDescription
enabledbooleantrueIf false, prevents auto-fetching

Return Values

PropertyTypeDescription
dataT | nullThe fetched data. Defaults to null
loadingbooleantrue while fetching, false when complete
errorError | nullContains error details if the fetch fails
retry() => voidA function to manually retry the request

๐Ÿ–ฑ๏ธ useHover Hook

A custom React hook that detects whether an element is being hovered over. It returns a boolean value indicating the hover state.


๐Ÿ”ง Usage

import { useRef } from "react";
import { useHover } from "./useHover";

function Component() {
  const ref = useRef<HTMLDivElement>(null);
  const isHovered = useHover(ref);

  return (
    <div
      ref={ref}
      style={{ backgroundColor: isHovered ? "lightblue" : "white" }}
    >
      Hover over me!
    </div>
  );
}

๐Ÿ›  API

useHover<T extends HTMLElement | null>(ref: RefObject<T> | null): boolean

Parameters

ParameterTypeDescription
refRefObjectnullA React ref object pointing to an HTMLElement.

Return Value

TypeDescription
booleantrue if the element is hovered, false otherwise.
Type ParametersT extends HTMLElement \| null: The type of element the ref refers to (automatically inferred).

โŒ› useIdle ๐Ÿ’ค

React hook that detects user inactivity after a specified timeout.

Parameters

  • timeout: number - Inactivity duration in milliseconds (default: 30000)

Returns

  • isIdle: boolean - Current idle state

Features

  • Monitors common user interactions:
    • Mouse movement
    • Keyboard activity
    • Scrolling
    • Clicks
    • Touch events
  • Automatically resets timer on activity
  • Safe for server-side rendering
  • Cleans up listeners on unmount

Usage

function App() {
  const isIdle = useIdle(10000); //

  return (
    <div style={{ color: isIdle ? "gray" : "green" }}>
  {isIdle ? "System idle โณ" : "Active ๐Ÿ’ป"}
  </div>
);

๐Ÿ‘† useLongPress ๐Ÿ•’

React hook for detecting long press interactions on elements, supporting both mouse and touch events.

Parameters

  • callback: (event: PressEvent, position: Position) => void - Function called when long press is detected
  • options: LongPressOptions - Configuration options object

Options

interface LongPressOptions {
  threshold?: number;        // Duration before triggering (ms), default: 400
  moveThreshold?: number;    // Maximum movement allowed (px), default: 10
  preventDefault?: boolean;  // Prevent default events, default: true
  disabled?: boolean;       // Disable the hook, default: false
  onStart?: (event: PressEvent, position: Position) => void;
  onFinish?: (event: PressEvent, position: Position, duration: number) => void;
  onCancel?: (event: PressEvent, position: Position) => void;
  onMove?: (event: PressEvent, position: Position) => void;
}

Returns

Object containing event handlers to spread onto the target element:

interface LongPressHandlers {
onMouseDown: (event: React.MouseEvent) => void;
onMouseUp: (event: React.MouseEvent) => void;
onMouseLeave: (event: React.MouseEvent) => void;
onMouseMove: (event: React.MouseEvent) => void;
onTouchStart: (event: React.TouchEvent) => void;
onTouchEnd: (event: React.TouchEvent) => void;
onTouchMove: (event: React.TouchEvent) => void;
}

Features

  • ๐Ÿ–ฑ๏ธ Supports both mouse and touch events
  • ๐Ÿ“ Configurable movement threshold
  • โฑ๏ธ Adjustable timing threshold
  • ๐Ÿšซ Cancel on movement exceeding threshold
  • ๐Ÿ“ Provides position information
  • โ™ฟ Accessibility through event prevention control
  • ๐Ÿ”„ Lifecycle callbacks for press states

Notes

  • Long press is triggered after holding for the specified threshold duration
  • Cancels if movement exceeds moveThreshold
  • Provides position coordinates for all events
  • Cleans up timers automatically
  • Can be disabled dynamically
  • Supports custom callbacks for different press states

๐Ÿ“ฑ useMobile ๐Ÿ“Š

React hook for detecting mobile viewport width with debounced updates.

Returns

  • boolean - true if viewport width is less than 768px (mobile breakpoint)

Usage

function App() {
  const isMobile = useMobile();

  return (
    <div>
      {isMobile ? "Mobile View!" : "Desktop View!"}
    </div>
  );
}

๐Ÿ–ฑ๏ธ useMousePosition ๐Ÿ“

React hook for tracking mouse position globally and relative to a specific element.

Returns

  • position: Position - Object containing all position coordinates
  • ref: React.Ref<T> - Reference to attach to tracked element

Position Object

interface Position {
  x: number;              // Global mouse X position
  y: number;              // Global mouse Y position
  elementX?: number;      // Mouse X position relative to element
  elementY?: number;      // Mouse Y position relative to element
  elementPositionX?: number;  // Element's X position on page
  elementPositionY?: number;  // Element's Y position on page
}

Type Parameters

  • T extends HTMLElement - Type of the element to track

Features

  • ๐ŸŒ Tracks global mouse position
  • ๐Ÿ“ Provides element-relative coordinates
  • ๐Ÿ“ Calculates element position on page
  • ๐Ÿ”„ Real-time updates
  • ๐Ÿงน Automatic cleanup of event listeners
  • ๐Ÿ’ช TypeScript support

Usage

function MouseTracker() {
  const [position, ref] = useMousePosition<HTMLDivElement>();

  return (
    <div ref={ref}>
      {position.elementX !== undefined && (
          <div
            style={{
              position: "absolute",
              left: position.elementX,
              top: position.elementY,
              width: "10px",
              height: "10px",
              background: "red",
              borderRadius: "50%",
              transform: "translate(-50%, -50%)",
  }}
  />
)}
  </div>
);
}

๐ŸŒ useOnlineStatus ๐Ÿ“ถ

React hook for monitoring the user's internet connection status in real-time.

Returns

  • boolean - Current online status
  • true - User is online
  • false - User is offline

Features

  • ๐Ÿ”„ Real-time connection monitoring
  • ๐ŸŒ Browser-compatible checks
  • ๐Ÿ”Œ Automatic event handling
  • ๐Ÿงน Cleanup on unmount
  • ๐ŸŽฏ SSR-friendly
  • โšก Zero configuration

Usage

function App() {
  const isOnline = useOnlineStatus();

  return (
    <div style={{ padding: "2rem", fontFamily: "sans-serif" }}>
      <h1>Network Status</h1>
      <p>
        You are currently{" "}
        <span style={{ fontWeight: "bold", color: isOnline ? "green" : "red" }}>
          {isOnline ? "Online" : "Offline"}
        </span>
        .
      </p>
    </div>
  );
}

๐Ÿ“‘ usePageTitle ๐Ÿ”ค

React hook for dynamically managing the document title with automatic cleanup.

Parameters

  • title: string - The new title to set for the document

Usage

function App() {
  usePageTitle("My Awesome Page");

  return (
    <div>
      <h1>My Awesome Page</h1>
      {/* Your content */}
    </div>
  );
}

๐Ÿ“œ useScrollPosition ๐Ÿ”

React hook for tracking window scroll position with performance optimization.

Returns

  • number - Current vertical scroll position in pixels

Usage

function App() {
  const scrollPosition = useScrollPosition();

  return (
    <div>
      <header style={{
        position: "fixed",
        backgroundColor: scrollPosition > 100 ? "#fff" : "transparent"
      }}>
        Scrolled: {scrollPosition}px
      </header>
      <main>
        {/* Your content */}
      </main>
    </div>
  );
}

๐Ÿ”„ useToggle ๐ŸŽš๏ธ

React hook for managing boolean state with a simple toggle function.

Parameters

  • initialValue?: boolean - Initial state value (default: false)

Returns

[boolean, () => void]

Usage

function App() {
  const [isOn, toggle] = useToggle(false);
  return (
    <div>
      <p>{isOn ? "ON" : "OFF"}</p>
      <button onClick={toggle}>Toggle</button>
    </div>
  );
}

โœ‚๏ธ useTruncate ๐Ÿ“

React hook for truncating text strings with ellipsis.

Returns

{
    truncate: (text: string, length: number) => string
}

Parameters for truncate function

  • text: string - Text to truncate (default: '')
  • length: number - Maximum length before truncation (default: 0)

Usage

function MessagePreview() {
  const { truncate } = useTruncate();
  
  return (
    <div className="message">
      <strong>{truncate("Sender Name", 10)}</strong>
      <p>{truncate("This is the message content", 25)}</p>
    </div>
  );
}

๐Ÿ–ฅ๏ธ useWindowSize ๐Ÿ“

React hook for tracking browser window dimensions with real-time updates.

Returns

{
  width: number,   // Current window width in pixels
  height: number   // Current window height in pixels
}

Usage

function App() {
  const { width, height } = useWindowSize();

  return (
    <div>
      <p>Window Width: {width}px</p>
      <p>Window Height: {height}px</p>
    </div>
  );
}
1.0.0

5 months ago

0.0.3

5 months ago

0.0.2

5 months ago

0.0.1

5 months ago