MCPcopy Index your code
hub / github.com/djkepa/custom-react-hooks

github.com/djkepa/custom-react-hooks @v2.0.9

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.0.9 ↗ · + Follow
173 symbols 426 edges 135 files 38 documented · 22%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Custom React Hooks Logo

<a href="https://www.npmjs.com/package/@custom-react-hooks/all">
  <img src="https://img.shields.io/npm/v/@custom-react-hooks/all.svg"
</a>
<a href="https://github.com/djkepa/custom-react-hooks/blob/main/LICENSE">
  <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License" />
</a>
<a href="https://github.com/djkepa/custom-react-hooks/stargazers">
  <img src="https://img.shields.io/github/stars/djkepa/custom-react-hooks.svg" alt="GitHub Stars" />
</a>
<a href="https://github.com/djkepa/custom-react-hooks/network">
  <img src="https://img.shields.io/github/forks/djkepa/custom-react-hooks.svg" alt="GitHub Forks" />
</a>
<a href="https://github.com/djkepa/custom-react-hooks/issues">
  <img src="https://img.shields.io/github/issues/djkepa/custom-react-hooks.svg" alt="GitHub Issues" />
</a>

A collection of reusable and well-documented custom React hooks for supercharging your React applications. These hooks cover a wide range of functionalities, making it easier for you to build dynamic and interactive user interfaces.

Custom React Hooks Library

Website

https://custom-react-hooks-live.vercel.app

🌟 Table of Contents

🚀 Installation

Choose and install individual hooks that suit your project needs, or install the entire collection for a full suite of utilities.

Installing All Hooks

If you prefer to have all hooks at your disposal, you can install the entire collection:

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Installing Specific Hooks

Each hook is a standalone package, and you can install them individually using npm or yarn:

npm install @custom-react-hooks/use-async

or

yarn add @custom-react-hooks/use-async

Importing the Hook

The useExample hook must be imported using a named import as shown below:

Named Import:

import { useExample } from '@custom-react-hooks/use-example';

This approach ensures that the hook integrates seamlessly into your project, maintaining consistency and predictability in how you use our package.

📚 Hooks List

🆕 New in Version 2.0.0

useAsync Hook

The useAsync hook simplifies the handling of asynchronous operations in React applications, such as data fetching or any other promise-returning functions. It provides a structured way to track the status and outcome of async operations.

Features

  • Automated Execution: Optionally executes the async function automatically on component mount.
  • Manual Execution: Provides a function to manually trigger the async operation.
  • Status and Error Tracking: Tracks the status of the async operation and captures any errors.
  • SSR Compatibility: Safe for server-side rendering, with checks to prevent automatic execution on the server.
  • Value Management: Manages the value returned from the async operation.

Installation

Choose and install individual hooks that suit your project needs, or install the entire collection for a full suite of utilities.

Installing Only Current Hooks

npm install @custom-react-hooks/use-async

or

yarn add @custom-react-hooks/use-async

Installing All Hooks

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Usage

import React, { useState } from 'react';
import { useAsync } from '@custom-react-hooks/all';

const fetchData = async (endpoint) => {
  const response = await fetch(endpoint);
  if (!response.ok) {
    throw new Error(`Failed to fetch from ${endpoint}`);
  }
  return response.json();
};

const AsyncComponent = () => {
  const [endpoint, setEndpoint] = useState('');
  const [simulateError, setSimulateError] = useState(false);
  const { execute, status, value: data, error } = useAsync(() => fetchData(endpoint), false);

  const handleFetch = () => {
    if (simulateError) {
      setEndpoint('https://jsonplaceholder.typicode.com/todos/1');
    }
    execute();
  };

  return (



      <input
        type="text"
        value={endpoint}
        onChange={(e) => setEndpoint(e.target.value)}
        placeholder="Enter API endpoint"
      />
      <button onClick={handleFetch}>Fetch Data</button>



        <label>
          <input
            type="checkbox"
            checked={simulateError}
            onChange={() => setSimulateError(!simulateError)}
          />
          Simulate Error
        </label>




      {status === 'pending' && 

Loading...

}
      {status === 'error' && 

Error: {error?.message}

}
      {status === 'success' && (



          <h3>Data:</h3>
          <pre>{JSON.stringify(data, null, 2)}</pre>



      )}



  );
};

export default AsyncComponent;

In this example, the useAsync hook is used to perform an asynchronous data fetch operation.

API Reference

Parameters

  • asyncFunction (Function): The asynchronous function to execute.
  • immediate (Boolean, optional): A boolean indicating whether the async function should be executed immediately on component mount. Defaults to false.

Returns

An object with the following properties:

  • execute (Function): A function to trigger the async operation.
  • status (String): The current status of the async operation (idle, pending, success, error).
  • value (Any): The value returned from the async operation.
  • error (Error | null): Any error that occurred during the execution.

Use Cases

  1. API Data Fetching: Fetching data from an API when a component mounts or based on user actions.

  2. Form Submission Handling: Managing asynchronous form submissions to a server, including loading states and error handling.

  3. Lazy Loading: Dynamically loading components or data based on certain conditions or user interactions.

  4. Web API Interactions: Simplifying the use of asynchronous Web APIs (like geolocation or camera access).

  5. File Uploads: Handling the asynchronous process of file uploads, including progress tracking and error management.

  6. Real-time Data Updates: Managing WebSocket connections or server polling for live data updates.

  7. Complex Calculations/Processing: Executing and managing state for asynchronous complex calculations, such as those using Web Workers.

  8. Third-party Service Integration: Facilitating interactions with asynchronous third-party services (e.g., payment gateways, social media APIs).

  9. Conditional Async Operations: Executing asynchronous tasks based on specific conditions or inputs.

  10. Sequencing Async Operations: Coordinating multiple dependent asynchronous operations in sequence.

Contributing

Contributions to enhance useAsync are highly encouraged. Feel free to submit issues or pull requests to the repository.

useClickOutside Hook

The useClickOutside hook is designed to detect and handle clicks outside of a specified element or set of elements. This is particularly useful for closing modal windows, dropdowns, and other components when a user interacts outside of them.

Features

  • Element Focus Management: Detects clicks outside of the specified element(s), which is essential for managing the focus and closing modal windows, dropdowns, and other components.
  • Customizable Event Listening: Listens for specific events like mousedown and touchstart to determine outside clicks, with the option to customize the events.
  • Dynamic Detection Control: Provides the ability to enable or disable the click outside detection dynamically, which offers flexible integration with various UI state requirements.
  • Ref Exclusion: Allows for the exclusion of certain elements (by refs) from triggering the outside click logic, which is useful when certain elements within the component should not close it.
  • Multiple Element Support: Can handle multiple elements as an array of refs, which is great for complex components that may consist of disjointed elements.
  • Simple Integration: Easy to integrate into existing components with minimal changes required to the existing structure.

Installation

Choose and install individual hooks that suit your project needs, or install the entire collection for a full suite of utilities.

Installing Only Current Hooks

npm install @custom-react-hooks/use-click-outside

or

yarn add @custom-react-hooks/use-click-outside

Installing All Hooks

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Usage

Here's an example of how to use the useClickOutside hook in a modal component:

import React, { useState, useRef } from 'react';
import { useClickOutside } from '@custom-react-hooks/all';

const Modal = ({ onClose }) => {
  const modalRef = useRef(null);

  useClickOutside(modalRef, onClose);

  return (





Modal content goes here


      <button onClick={onClose}>Close Modal</button>



  );
};

const ClickOutsideComponent = () => {
  const [isModalOpen, setModalOpen] = useState(false);

  const openModal = () => setModalOpen(true);
  const closeModal = () => setModalOpen(false);

  return (



      <button onClick={openModal}>Open Modal</button>
      {isModalOpen && <Modal onClose={closeModal} />}



  );
};

export default ClickOutsideComponent;

In the above example, clicking outside the `

containing the modal content will trigger theonClose` function.

API Reference

Parameters

  • refs (RefObject | RefObject[]): A ref or an array of refs to the element(s) you want to detect outside clicks on.
  • callback (function): A callback function that will be called when a click outside the detected elements occurs.
  • events (string[], optional): An array of event names to listen for clicks. Defaults to ['mousedown', 'touchstart'].
  • enableDetection (boolean, optional): A boolean to enable or disable click detection. Defaults to true.
  • ignoreRefs (RefObject[], optional): An array of ref objects for elements that, when clicked, should not trigger the callback.

Use Cases

  • Closing Modals or Popups: Automatically close a modal or popup when a user clicks outside of it.
  • Dropdown Menus: Collapse dropdown menus when the user interacts with other parts of the application.
  • Context Menus: Hide context menus or custom right-click menus when clicking elsewhere on the page.
  • Form Validation or Submission: Trigger form validation or submission when clicking outside of a form area.
  • Toggling UI Elements: Toggle the visibility of UI elements like sidebars or tooltips when clicking outside of them.

Notes

  • Ensure the elements referenced by refs are mounted when the hook is called.
  • The hook must be called within a functional component body or another custom hook.

Contributing

Feel free to contribute to the development of this hook by submitting issues or pull requests to the repository.

useClipboard Hook

useClipboard is a React hook that provides a comprehensive interface for clipboard operations. It offers advanced features like automatic clipboard content reading, change detection, and polling capabilities, making it perfect for building sophisticated clipboard-aware applications.

Features

  • Copy and Paste: Offers methods to both copy text to and paste text from the clipboard.
  • Clipboard Content Reading: Automatically reads and tracks clipboard content with real-time updates.
  • Content Change Detection: Detects when clipboard content changes and provides callbacks.
  • Polling Support: Optional polling to continuously monitor clipboard changes.
  • Smart State Management: Tracks clipboard content, loading states, and operation status.
  • Asynchronous API: Uses promise-based Clipboard API methods for non-blocking operations.
  • Status and Error Reporting: Returns the status of clipbo

Extension points exported contracts — how you extend this code

ShareData (Interface)
(no doc)
packages/use-share/src/index.tsx
NetworkInformation (Interface)
(no doc)
packages/use-network/src/index.tsx
OrientationState (Interface)
(no doc)
packages/use-orientation/src/index.tsx
UseImageLoadOptions (Interface)
(no doc)
packages/use-image-load/src/index.tsx
UseAsyncReturn (Interface)
(no doc)
packages/use-async/src/index.tsx
UseOffscreenOptions (Interface)
(no doc)
packages/use-offscreen/src/index.tsx
UseStepOptions (Interface)
(no doc)
packages/use-step/src/index.tsx
UseFormReturnType (Interface)
(no doc)
packages/use-form/src/index.tsx

Core symbols most depended-on inside this repo

set
called by 27
packages/use-fetch/src/index.tsx
get
called by 23
packages/use-fetch/src/index.tsx
useClipboard
called by 16
packages/use-clipboard/src/index.tsx
useVirtual
called by 12
packages/use-virtual/src/index.tsx
useCache
called by 11
packages/use-cache/src/index.tsx
useHistoryState
called by 11
packages/use-history-state/src/index.tsx
useShare
called by 10
packages/use-share/src/index.tsx
useOffscreen
called by 10
packages/use-offscreen/src/index.tsx

Shape

Function 108
Interface 43
Method 14
Class 8

Languages

TypeScript100%

Modules by API surface

packages/use-fetch/src/index.tsx12 symbols
packages/use-worker/test/useWorker.test.tsx7 symbols
packages/use-network/src/index.tsx7 symbols
packages/use-status/src/index.tsx6 symbols
packages/use-form/src/index.tsx6 symbols
packages/use-websocket/test/useWebSocket.test.tsx5 symbols
packages/use-share/src/index.tsx5 symbols
packages/use-history-state/src/index.tsx5 symbols
packages/use-websocket/src/index.tsx4 symbols
packages/use-virtual/src/index.tsx4 symbols
packages/use-offscreen/src/index.tsx4 symbols
packages/use-mouse/src/index.tsx4 symbols

For agents

$ claude mcp add custom-react-hooks \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page