0.0.3 • Published 4 months ago

usehook-react v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

React custom hooks for faster development.

npm npm downloads license

Below is given full :page_facing_up: documentation with few use cases for each hook.

:bulb: Getting Started

usehook-react - Featured Custom Hooks

Dive into the world of usehook-react – a curated collection of React custom hooks tailored to enhance your application development experience. From efficient data caching with useCacheQuery to managing styles dynamically with useCss, each hook is crafted to solve specific challenges, making your code more modular and your components more versatile.

Explore the versatility of usehook-react:

State and Data Handling:

  • useCacheQuery: Efficient caching and fetching of data.
  • useFetchWithRetry: Perform API requests with automatic retry on failure.
  • useLocalStorage and useSessionStorage: Manage data persistence in local and session storage.

User Interaction:

  • useOnClickOutside: Detect clicks outside a specified element.
  • useKeyPress: Capture keyboard events for user interaction.
  • useHover: Determine whether an element is being hovered over.

Device and Browser Features:

  • useGeoLocation: Access geolocation coordinates effortlessly.
  • useDeviceOrientation: Gather device orientation information.
  • useFullScreen: Enable full-screen mode for specified elements.

UI and Presentation:

  • useWindowSize: Keep track of the window size dynamically.
  • useMeasure: Measure dimensions of elements on the page.
  • useCss: Dynamically apply styles to your components.

... and many more! Empower your React applications with these hooks to simplify complex tasks and elevate your development workflow.

useCacheQuery

This React hook enables data fetching with caching support. It fetches data from a specified URL, caches it, and provides methods to refetch, manually remove the cache, and cancel ongoing fetch requests.

Use Cases

Here are some common scenarios where you might want to use the useCacheQuery hook:

Offline Data Access:

  • Enable caching for data that needs to be accessible even when the user is offline.
  • Use the cached data when the network is unavailable to maintain a smooth user experience.

Reducing Network Requests:

  • Avoid unnecessary network requests by checking and using cached data before initiating a new request.
  • This helps in reducing server load and speeds up your application.

Debugging and Manual Cache Control:

  • Enable debug logging to gain insights into caching behavior during development.
  • Manually control cache by triggering a cache removal or canceling an ongoing fetch.

Selective Data Fetching:

  • Fetch data only when needed, based on the isEnabled parameter.
  • This allows you to control when caching and fetching should occur.
  import React from 'react';
  import { useCacheQuery } from 'usehook-react';

  function CachedDataComponent() {
    const cacheKey = 'exampleCache';
    const url = 'https://jsonplaceholder.typicode.com/users';
    const isEnabled = true; // Enable caching
    const debug = true; // Enable debug logging

    const { data, loading, error, refetch, remove, isRemoving, cancel } = useCacheQuery({
      cacheKey,
      url,
      isEnabled,
      debug,
    });

    // Your component logic here...

    return (
      <div>
        {/* Render your UI using data, loading, error, and other state values */}
        {loading && <p>Loading...</p>}
        {error && <p>Error fetching data.</p>}
        {data.map(item => (
          <div key={item.id}>{item.name}</div>
        ))}

        {/* Trigger a manual refetch */}
        <button onClick={refetch}>Refetch Data</button>

        {/* Manually remove the cache for the given key */}
        <button onClick={remove} disabled={isRemoving}>
          {isRemoving ? 'Removing Cache...' : 'Remove Cache'}
        </button>

        {/* Manually cancel an ongoing fetch */}
        <button onClick={cancel}>Cancel Fetch</button>
      </div>
    );
  }

Code Breakdown

Parameters

  • cacheKey (string): A unique key for the cache, typically representing the type of data being cached.

  • url (string): The URL to fetch data from.

  • isEnabled (optional) (boolean): A boolean indicating whether caching and fetching are enabled.

  • options (optional) (RequestInit): Additional options to customize the fetch request.

  • debug (optional) (boolean): A boolean indicating whether to enable debug logging.

Return Value

An object with the following properties and methods:

  • data (any[]): The fetched data.

  • loading (boolean): A boolean indicating whether the data is currently being fetched.

  • error (boolean): A boolean indicating whether an error occurred during fetching.

  • refetch (): A function to manually trigger a data refetch.

  • remove (): A function to manually remove the cache for the given key.

  • cancel (): A function to manually cancel an ongoing fetch.

  • isRemoving (boolean): A boolean indicating whether the cache removal is in progress.

usePageVisibility

This React hook tracks page visibility using the browser's Page Visibility API. It returns a boolean value indicating whether the page is currently visible or not.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. Pausing and Resuming Videos or Animations:

    • When the page is hidden, pause the video or animation to save resources and improve performance.
    • Resume playback when the page becomes visible again.
  2. Saving User Progress or Data:

    • If the user leaves the page, you might want to save their progress or data to avoid losing it.
    • Use this hook to trigger a save operation when the page becomes hidden.
  3. Tracking User Engagement:

    • Track how long users are actually viewing your content by measuring the time the page is visible.
  4. Optimizing Resource-Intensive Tasks:

    • Defer non-critical tasks like fetching data or rendering complex components until the page is visible, improving perceived performance.

Example

    import React, { useEffect } from 'react';
    import { usePageVisibility } from 'usehook-react';

    function MyComponent() {
        const isVisible = usePageVisibility();

        useEffect(() => {
            if (isVisible) {
                // Play video or resume other activities
            } else {
                // Pause video or save user progress
            }
        }, [isVisible]);

        return (
            // Your component JSX
        );
    }

Code Breakdown

Parameters:

  • None

Return Value:

  • boolean: true if the page is visible, false otherwise

useThrottle

This React hook provides throttling functionality for a given callback function, limiting the rate at which the callback can be invoked. It helps optimize performance by preventing excessive calls, especially in scenarios like handling user input or scroll events.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. User Input Handling:

    • Throttle the execution of a callback function tied to user input (e.g., search input) to avoid overwhelming API requests or updates.
  2. Scroll Event Optimization:

    • Limit the frequency of scroll-related operations (e.g., infinite scrolling, parallax effects) to enhance the user experience and reduce unnecessary computations.
  3. Resize Event Handling:

    • Throttle the callback triggered by window resize events to prevent rapid adjustments and improve performance.

Example

    import React, { useState, useEffect } from 'react';
    import { useThrottle } from 'usehook-react';

    function ThrottledComponent() {
        const [scrollPosition, setScrollPosition] = useState(0);

        // Throttle the updateScrollPosition function to avoid excessive calls
        const throttledUpdateScroll = useThrottle(updateScrollPosition, 200);

        useEffect(() => {
            // Attach the throttled function to the scroll event
            window.addEventListener('scroll', throttledUpdateScroll);

            // Cleanup the event listener on component unmount
            return () => {
                window.removeEventListener('scroll', throttledUpdateScroll);
            };
        }, [throttledUpdateScroll]);

        // Function to be throttled
        function updateScrollPosition() {
            setScrollPosition(window.scrollY);
        }

        return (
            <div>
                <p>Current Scroll Position: {scrollPosition}</p>
                {/* Your component JSX */}
            </div>
        );
    }

Code Breakdown

Parameters

  • callback: The callback function to be throttled.

    • Type: (...args: any[]) => void
  • delay: The delay (in milliseconds) between consecutive invocations of the throttled callback.

    • Type: number

Return Value

  • throttledCallback: The throttled version of the original callback function.

useToggle

This React hook provides a simple and flexible way to manage boolean state toggling. It returns an object with various functions to manipulate and interact with the boolean value.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. Toggle UI Elements:

    • Toggle the visibility or state of UI elements in response to user interactions.
  2. Control Conditional Rendering:

    • Conditionally render components based on the toggled boolean value.
  3. Form Input Handling:

    • Manage the state of checkboxes or toggle switches in forms.
  4. Toggle Between Two States:

    • Easily toggle between true and false states with convenient functions.

Example

    import React from 'react';
    import { useToggle } from 'usehook-react';

    function ToggleComponent() {
        const { value, toggle, setTrue, setFalse, toggleWithCallback } = useToggle();

        return (
            <div>
                <p>Current Value: {value ? 'True' : 'False'}</p>
                
                <button onClick={toggle}>Toggle</button>
                <button onClick={setTrue}>Set True</button>
                <button onClick={setFalse}>Set False</button>
                
                <button onClick={() => toggleWithCallback((newValue) => console.log(`Callback: ${newValue}`))}>
                    Toggle with Callback
                </button>
                
                {/* Your component JSX */}
            </div>
        );
    }

Code Breakdown

Parameters

  • initialValue: The initial boolean value. Defaults to false.
    • Type: boolean

Return Value

  • ToggleResult: An object containing the following properties and functions:

    • value: The current boolean value.

      • Type: boolean
    • toggle: A function to toggle the boolean value.

      • Type: () => void
    • setTrue: A function to set the boolean value to true.

      • Type: () => void
    • setFalse: A function to set the boolean value to false.

      • Type: () => void
    • toggleWithCallback: A function to toggle the boolean value with an optional callback, which receives the updated boolean value.

      • Type: (callback?: (value: boolean) => void) => void

useDebounce

This React hook provides debouncing functionality for a given value, delaying the update until a specified time has passed without further changes. It is particularly useful for scenarios where you want to delay the execution of a function, such as in the case of handling user input.

Example

    import React, { useState } from 'react';
    import { useDebounce } from 'usehook-react';

    function DebouncedComponent() {
        const [inputValue, setInputValue] = useState('');
        
        // Debounce the input value to avoid frequent updates
        const debouncedInputValue = useDebounce(inputValue, 500);

        return (
            <div>
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    placeholder="Type something..."
                />
                
                <p>Debounced Value: {debouncedInputValue}</p>
                
                {/* Your component JSX */}
            </div>
        );
    }

Code Breakdown

Parameters

  • value: The value to be debounced.

    • Type: any
  • delay: The delay (in milliseconds) before updating the debounced value.

    • Type: number

Return Value

  • debouncedValue: The debounced version of the input value.

useCopyURL

This React hook provides functionality to copy the current page's URL to the clipboard. It is useful in scenarios where you want to enable users to easily share or save the current page's URL.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. Shareable Links:

    • Enable users to quickly copy the URL of the current page for sharing.
  2. Save URL to Clipboard:

    • Implement a "Copy Link" button to allow users to copy the current page's URL for later use.
  3. Integration with UI Components:

    • Integrate with UI components, such as buttons or icons, to provide a seamless user experience.

Example

  import React from 'react';
  import { useCopyURL } from 'usehook-react';

  function CopyURLComponent() {
      const { copyURL } = useCopyURL();

      return (
          <div>
              <button onClick={copyURL}>Copy URL</button>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

  • An object with a single function:
    • copyURL: A function to copy the current page's URL to the clipboard.

useWindowSize

This React hook provides a simple way to track the current size of the browser window. It returns an object with width and height properties representing the window's dimensions.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. Responsive UI Elements:

    • Dynamically adjust the size or layout of UI elements based on the window size.
  2. Media Queries:

    • Create custom media queries in your components by utilizing the window size information.
  3. Conditional Rendering:

    • Conditionally render components based on different window size breakpoints.

Example

  import React from 'react';
  import { useWindowSize } from 'usehook-react';

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

      return (
          <div>
              <p>Window Width: {width}px</p>
              <p>Window Height: {height}px</p>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

  • An object with two properties:
    • width: The current width of the browser window.
      • Type: number
    • height: The current height of the browser window.
      • Type: number

useWriteToClipboard

This React hook provides functionality to write text to the clipboard and tracks the success of the operation. It returns an object with isCopied representing the success state and writeToClipboard to trigger the copy operation.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. Copy-to-Clipboard Buttons:

    • Implement buttons that allow users to copy certain text to the clipboard.
  2. Feedback for Copy Operations:

    • Provide visual feedback to users indicating whether the copy operation was successful.
  3. Interactive UI Components:

    • Integrate with UI components to enable copying of dynamic or user-generated text.

Example

  import React from 'react';
  import { useWriteToClipboard } from 'usehook-react';

  function ClipboardComponent() {
      const { isCopied, writeToClipboard } = useWriteToClipboard();
      
      const textToCopy = "Hello, Clipboard!";

      return (
          <div>
              <button onClick={() => writeToClipboard(textToCopy)}>
                  Copy to Clipboard
              </button>
              {isCopied && <p>Text Copied!</p>}
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

  • An object with two properties:
    • isCopied: A boolean indicating whether the text was successfully copied to the clipboard.
      • Type: boolean
    • writeToClipboard: A function to write the provided text to the clipboard.
      • Type: (text: string) => void

useReadFromClipboard

This React hook provides functionality to read text from the clipboard and tracks the result. It returns an object with clipboardText representing the text read from the clipboard and readFromClipboard to trigger the read operation.

Use Cases

Here are some common scenarios where you might want to use this hook:

  1. Paste Operations:

    • Implement components that allow users to paste text from the clipboard.
  2. Interactive UI Components:

    • Integrate with UI components to display or manipulate text read from the clipboard.
  3. Clipboard Monitoring:

    • Read text from the clipboard to monitor and respond to changes.

Example

  import React from 'react';
  import { useReadFromClipboard } from 'usehook-react';

  function ClipboardReaderComponent() {
      const { clipboardText, readFromClipboard } = useReadFromClipboard();

      return (
          <div>
              <button onClick={readFromClipboard}>
                  Read from Clipboard
              </button>
              {clipboardText && <p>Clipboard Text: {clipboardText}</p>}
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

  • An object with two properties:
    • clipboardText: The text read from the clipboard or null if the operation failed.
      • Type: string | null
    • readFromClipboard: A function to trigger the read operation from the clipboard.
      • Type: () => void

usePrevious

This React hook keeps track of the previous value of a state or prop, making it useful for comparing changes. It returns the previous value.

Example

  import React, { useState, useEffect } from 'react';
  import { usePrevious } from 'usehook-react';

  function PreviousValueComponent() {
      const [count, setCount] = useState(0);
      const previousCount = usePrevious(count);

      useEffect(() => {
          // Access the previous value
          console.log(`Previous Count: ${previousCount}`);
      }, [count, previousCount]);

      return (
          <div>
              <p>Current Count: {count}</p>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • value: The current value to track.
    • Type: T

Return Value

  • The previous value.
    • Type: T | undefined

useMediaQuery

This React hook dynamically updates state based on the current media query, facilitating responsive design. It returns a boolean value indicating whether the media query currently matches.

Example

  import React from 'react';
  import { useMediaQuery } from 'usehook-react';

  function ResponsiveComponent() {
      const isSmallScreen = useMediaQuery('(max-width: 600px)');

      return (
          <div>
              {isSmallScreen ? (
                  <p>Currently viewing on a small screen</p>
              ) : (
                  <p>Currently viewing on a larger screen</p>
              )}
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • query: The media query to match.
    • Type: string

Return Value

  • Whether the media query currently matches.
    • Type: boolean

useFetch

This React hook simplifies data fetching by providing an easy-to-use interface with options for URL, request options, and initial data. It returns an object with data, loading, error, and refetch properties to handle the fetch operation's state.

Example

  import React from 'react';
  import { useFetch } from 'usehook-react';

  function FetchComponent() {
      const { data, loading, error, refetch } = useFetch({
          url: 'https://api.example.com/data',
          options: {
              method: 'GET',
              headers: {
                  'Content-Type': 'application/json',
              },
          },
          initialData: null,
      });

      return (
          <div>
              {loading && <p>Loading...</p>}
              {error && <p>Error: {error.message}</p>}
              {data && (
                  <>
                      <p>Data: {JSON.stringify(data)}</p>
                      <button onClick={refetch}>Refetch Data</button>
                  </>
              )}
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • url: The URL for the data fetch.

    • Type: string
  • options: Optional request options for the fetch operation.

    • Type: RequestInit | undefined
  • initialData: Initial data to set before fetching.

    • Type: T | undefined

useAsync

This React hook simplifies the management of asynchronous operations by providing an interface to handle loading, data, and errors. It returns an object with data, loading, error, and run properties, where run is a function to initiate the asynchronous operation.

Example

  import React from 'react';
  import { useAsync } from 'usehook-react';

  function AsyncComponent() {
      const fetchData = async () => {
          // Simulate an asynchronous operation
          return new Promise<string>((resolve) => {
              setTimeout(() => resolve('Async Data'), 2000);
          });
      };

      const { data, loading, error, run } = useAsync(fetchData);

      return (
          <div>
              {loading && <p>Loading...</p>}
              {error && <p>Error: {error.message}</p>}
              {data && <p>Data: {data}</p>}
              <button onClick={run}>Run Async Operation</button>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • asyncFunction: The asynchronous function to run.

    • Type: AsyncFunction<T>
  • immediate: Optional flag to determine whether to run the asynchronous function immediately.

    • Type: boolean
    • Default: true

Return Value

  • An object with the following properties:

    • data: The data obtained from the asynchronous operation or null.

      • Type: T | null
    • loading: A boolean indicating whether the asynchronous operation is in progress.

      • Type: boolean
    • error: An error object if the asynchronous operation encounters an error, otherwise null.

      • Type: Error | null
    • run: A function to manually trigger the asynchronous operation.

      • Type: () => void

useInterval

This React hook executes a function at a specified interval. It takes a callback function and the interval duration in milliseconds as parameters.

Example

  import React from 'react';
  import { useInterval } from 'usehook-react';

  function IntervalComponent() {
      const intervalCallback = () => {
          // Perform actions at the specified interval
          console.log('Interval Tick');
      };

      // Execute the callback every 1000 milliseconds (1 second)
      useInterval(intervalCallback, 1000);

      return (
          <div>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • callback: The function to be executed at the specified interval.

    • Type: IntervalFunction
  • delay: The interval duration in milliseconds. Pass null to stop the interval.

    • Type: number | null

Return Value

  • None (void)

useOnClickOutside

This React hook closes a component when the user clicks outside of it. It takes a reference to the component's DOM element (ref) and a callback function to be executed when a click outside occurs (callback).

Example

  import React, { useRef } from 'react';
  import { useOnClickOutside } from 'usehook-react';

  function ClickOutsideComponent() {
      const componentRef = useRef(null);

      const handleOutsideClick = () => {
          // Close the component or perform other actions
          console.log('Clicked outside the component');
      };

      // Attach click outside listener to the component
      useOnClickOutside(componentRef, handleOutsideClick);

      return (
          <div ref={componentRef}>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • ref: Reference to the component's DOM element.

    • Type: RefObject<T>
  • callback: Callback function to be executed when a click outside occurs.

    • Type: (event: MouseEvent) => void

Return Value

  • None (void)

useKeyPress

This React hook monitors and handles key presses. It takes the targetKey to monitor and a callback function to be executed when the specified key is pressed.

Example

  import React from 'react';
  import { useKeyPress } from 'usehook-react';

  function KeyPressComponent() {
      const handleKeyPress = () => {
          // Perform actions when the specified key is pressed
          console.log('Key Pressed');
      };

      // Monitor and handle the 'Enter' key press
      useKeyPress('Enter', handleKeyPress);

      return (
          <div>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • targetKey: The key to monitor.

    • Type: string
  • callback: Callback function to be executed when the specified key is pressed.

    • Type: () => void

Return Value

  • None (void)

useLocalStorage

This React hook syncs state with local storage. It takes a key to use for storing data in local storage and an initialState as the initial state value. It returns a tuple containing the state, a function to update the state, and a function to remove the stored data from local storage.

Example

  import React from 'react';
  import { useLocalStorage } from 'usehook-react';

  function LocalStorageComponent() {
      // Initialize with a key and initial state
      const [storedData, setStoredData, removeFromLocalStorage] = useLocalStorage('myKey', 'initialValue');

      return (
          <div>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • key: The key to use for storing data in local storage.

    • Type: string
  • initialState: The initial state value.

    • Type: T

Return Value

A tuple containing:

  • state: The current state value.

    • Type: T
  • setState: A function to update the state.

    • Type: Dispatch<SetStateAction<T>>
  • removeFromLocalStorage: A function to remove the stored data from local storage.

    • Type: () => void

useSessionStorage

This React hook syncs state with session storage. It takes a key to use for storing data in session storage and an initialState as the initial state value. It returns a tuple containing the state, a function to update the state, and a function to remove the stored data from session storage.

Example

  import React from 'react';
  import { useSessionStorage } from 'usehook-react';

  function SessionStorageComponent() {
      // Initialize with a key and initial state
      const [storedData, setStoredData, removeFromSessionStorage] = useSessionStorage('myKey', 'initialValue');

      return (
          <div>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • key: The key to use for storing data in session storage.

    • Type: string
  • initialState: The initial state value.

    • Type: T

Return Value

A tuple containing:

  • state: The current state value.

    • Type: T
  • setState: A function to update the state.

    • Type: Dispatch<SetStateAction<T>>
  • removeFromSessionStorage: A function to remove the stored data from session storage.

    • Type: () => void

useScroll

This React hook is designed to track the scroll position of the window. It provides real-time updates of both the horizontal and vertical scroll positions.

Use Cases

  1. Custom Animations or Effects: You can trigger animations or effects based on the scroll position, creating a dynamic and engaging user experience.

  2. Sticky Navigation: Implement sticky navigation bars that appear or disappear based on the user's scroll behavior.

  3. Lazy Loading: Load content or images lazily based on the scroll position, improving performance by only rendering what's currently visible.

Example

  import React, { useEffect } from 'react';
  import { useScroll } from 'usehook-react';

  function ScrollComponent() {
      const { x, y } = useScroll();

      useEffect(() => {
          // Your logic based on scroll position
          console.log(`Current scroll position: x=${x}, y=${y}`);
      }, [x, y]);

      return (
          // Your component JSX
      );
  }

Code Breakdown

Parameters

None

Return Value

An object representing the current scroll position.

  • x: The horizontal scroll position.
    • Type: number
  • y: The vertical scroll position.
    • Type: number

useHover

This React hook determines whether an element is currently being hovered over. It returns a boolean value indicating the hover state of the element.

Use Cases

  1. Conditional Rendering: Show or hide certain elements based on whether they are being hovered over.

  2. Styling Changes: Apply different styles to an element when it is being hovered, providing visual feedback to users.

  3. Event Triggering: Trigger specific actions or events when an element is hovered, such as displaying additional information.

Example

  import React from 'react';
  import { useHover } from 'usehook-react';

  function HoverComponent() {
      const isHovered = useHover();

      return (
          <div>
              {isHovered ? 'Hovered!' : 'Not Hovered'}
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

A boolean indicating whether the element is being hovered over.

useAnimationFrame

This React hook executes a callback on each frame of the browser's animation loop.

Use Cases

  1. Smooth Animations: Use this hook to create smooth and efficient animations by updating the state or manipulating the DOM on each animation frame.

  2. Game Development: Implement game-related logic that requires constant updates and calculations on each animation frame.

  3. Visual Effects: Apply dynamic visual effects or transitions that respond to the continuous animation loop.

Example

  import React from 'react';
  import { useAnimationFrame } from 'usehook-react';

  function AnimatedComponent() {
      useAnimationFrame(() => {
          // Your animation logic here
      });

      return (
          <div>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • callback: The function to be executed on each animation frame.
    • Type: () => void

Return Value

None (void)

useClipboard

This React hook provides functions to read from and write to the clipboard. It returns an object containing the current clipboard value, a function to write to the clipboard, and a function to read from the clipboard.

Use Cases

  1. Copy-Paste Operations: Utilize the hook to facilitate copy-paste functionality in your application.

  2. Clipboard Management: Keep track of the clipboard content within your components.

  3. User Interaction: Implement features where users can copy or paste content easily.

Example

  import React from 'react';
  import { useClipboard } from 'usehook-react';

  function ClipboardComponent() {
      const { value, writeToClipboard, readFromClipboard } = useClipboard();

      return (
          <div>
              <p>Current Clipboard Value: {value}</p>
              <button onClick={() => writeToClipboard("Hello, Clipboard!")}>Copy to Clipboard</button>
              <button onClick={readFromClipboard}>Read from Clipboard</button>
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

An object with the following properties:

  • value: The current clipboard value.
    • Type: string
  • writeToClipboard: A function to write to the clipboard.
    • Type: (text: string) => void
  • readFromClipboard: A function to read from the clipboard.
    • Type: () => void

useOnlineStatus

This React hook monitors the online/offline status of the user's device. It returns a boolean indicating whether the device is currently online.

Use Cases

  1. Network Status Display: Display network connectivity status in your application UI.

  2. Conditional Rendering: Conditionally render components or features based on the device's online status.

  3. Offline Mode: Implement features that adjust behavior when the device is offline.

Example

  import React from 'react';
  import { useOnlineStatus } from 'usehook-react';

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

      return (
          <div>
              <p>Device is {isOnline ? 'online' : 'offline'}.</p>
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

A boolean indicating whether the device is currently online.

useIdle

This React hook detects when the user becomes idle (no mouse or keyboard activity) and when they become active again. It returns a boolean indicating whether the user is currently idle.

Use Cases

  1. Automated Logout: Log out users automatically when they remain idle for a specific period.

  2. Energy Saving: Implement features that reduce energy consumption or turn off certain animations when the user is idle.

  3. Inactivity Alerts: Display alerts or notifications when the user has been idle for a certain duration.

Example

  import React from 'react';
  import { useIdle } from 'usehook-react';

  function IdleComponent() {
      const isIdle = useIdle({ timeout: 30000 }); // 30 seconds timeout

      return (
          <div>
              <p>{isIdle ? 'User is idle' : 'User is active'}</p>
          </div>
      );
  }

Code Breakdown

Parameters

  • options: An object with an optional timeout property (in milliseconds) to define the idle threshold.

Return Value

A boolean indicating whether the user is currently idle.

useHistory

This React hook provides access to the browser's history object, allowing programmatic navigation. It returns an object with methods and properties related to the browser's history.

Use Cases

  1. Programmatic Navigation: Navigate between different views or pages in a React application based on user actions or application logic.

  2. History Control: Implement custom controls for navigating backward or forward in the user's history.

  3. URL Manipulation: Dynamically update the URL without triggering a full page reload.

Example

  import React from 'react';
  import { useHistory } from 'usehook-react';

  function HistoryComponent() {
      const history = useHistory();

      const handleNavigation = () => {
          history.push('/new-page');
      };

      return (
          <div>
              <button onClick={handleNavigation}>Navigate to New Page</button>
          </div>
      );
  }

Code Breakdown

Return Value

An object with the following methods and properties:

  • push: Function to add a new entry to the browser's session history.
  • replace: Function to modify the current history entry.
  • go: Function to navigate to a specific entry in the history.
  • goBack: Function to navigate backward in the history.
  • goForward: Function to navigate forward in the history.
  • length: The number of elements in the history.
  • location: The current location object representing the URL.

useCookie

This React hook handles reading and writing cookies. It takes a cookieName as the name of the cookie and an optional options object with configuration options for the cookie. The hook returns an object with the current cookie value and methods to update and delete the cookie.

Use Cases

  1. User Authentication: Manage authentication tokens or session data stored in cookies.

  2. Persistent User Preferences: Store user preferences or settings in cookies for a personalized experience.

  3. Tracking: Use cookies to track user behavior or preferences.

Example

  import React from 'react';
  import { useCookie } from 'usehook-react';

  function CookieComponent() {
      const { value, updateCookie, deleteCookie } = useCookie('myCookie');

      const handleUpdateCookie = () => {
          updateCookie('newCookieValue', { expires: 365 });
      };

      return (
          <div>
              <p>Current Cookie Value: {value}</p>
              <button onClick={handleUpdateCookie}>Update Cookie</button>
              <button onClick={deleteCookie}>Delete Cookie</button>
          </div>
      );
  }

Code Breakdown

Parameters

  • cookieName: The name of the cookie.

    • Type: string
  • options (optional): An object with optional configuration options for the cookie.

    • Type: CookieOptions

Return Value

An object with the following properties and methods:

  • value: The current cookie value.

    • Type: string | null
  • updateCookie: Function to update the cookie with a new value and optional options.

    • Type: (newValue: string, options?: CookieOptions) => void
  • deleteCookie: Function to delete the cookie.

    • Type: () => void

useMeasure

This React hook measures the size and position of a DOM element. It returns an object with a ref to attach to the element and its dimensions.

Use Cases

  1. Responsive Design: Adapt the layout or styles based on the dimensions of a specific element.

  2. Dynamic Components: Dynamically adjust components based on the size of their container.

  3. Positioning: Position elements based on the measured dimensions of other elements.

Example

  import React from 'react';
  import { useMeasure } from 'usehook-react';

  function MeasureComponent() {
      const { ref, dimensions } = useMeasure();

      return (
          <div ref={ref}>
              <p>Element dimensions: {dimensions ? `${dimensions.width} x ${dimensions.height}` : 'not measured'}</p>
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

An object with the following properties:

  • ref: A ref to attach to the target element.
    • Type: React.RefObject<Element>
  • dimensions: The dimensions of the measured element.
    • Type: DOMRectReadOnly | null

useGeoLocation

This React hook retrieves and monitors the user's geolocation. It returns an object containing the current geolocation coordinates and any potential errors.

Use Cases

  1. Location-Based Features: Customize your application based on the user's current location.

  2. Mapping and Navigation: Implement maps or navigation features by utilizing real-time geolocation.

  3. Weather Apps: Display local weather conditions by fetching the user's location.

Example

  import React from 'react';
  import { useGeoLocation } from 'usehook-react';

  function GeoLocationComponent() {
      const { coords, error } = useGeoLocation();

      return (
          <div>
              {coords ? (
                  <p>
                      Latitude: {coords.latitude}, Longitude: {coords.longitude}, Accuracy: {coords.accuracy}
                  </p>
              ) : (
                  <p>Error fetching geolocation: {error.message}</p>
              )}
          </div>
      );
  }

Code Breakdown

Parameters

  • options (optional): An object with optional configuration options for geolocation.
    • Type: GeoLocationOptions

Return Value

An object with the following properties:

  • coords: The current geolocation coordinates.

    • Type:
      {
          latitude: number;
          longitude: number;
          accuracy: number;
          altitude?: number | null;
          altitudeAccuracy?: number | null;
          heading?: number | null;
          speed?: number | null;
      } | null
  • error: Any potential errors encountered during geolocation.

    • Type: Error

useDeviceOrientation

This React hook retrieves and monitors the orientation of the device. It returns an object containing the current device orientation and any potential errors.

Use Cases

  1. Augmented Reality: Develop augmented reality (AR) experiences by tracking the device's orientation.

  2. Gaming: Create games that respond to the user's device movements.

  3. Interactive UI: Implement interactive user interfaces that adapt based on the device's orientation.

Example

  import React from 'react';
  import { useDeviceOrientation } from 'usehook-react';

  function DeviceOrientationComponent() {
      const { alpha, beta, gamma, absolute, error } = useDeviceOrientation();

      return (
          <div>
              {alpha !== null ? (
                  <p>
                      Alpha: {alpha}, Beta: {beta}, Gamma: {gamma}, Absolute: {absolute ? 'Yes' : 'No'}
                  </p>
              ) : (
                  <p>Error fetching device orientation: {error.message}</p>
              )}
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

An object with the following properties:

  • alpha: The rotation around the z-axis.

    • Type: number | null
  • beta: The rotation around the x-axis.

    • Type: number | null
  • gamma: The rotation around the y-axis.

    • Type: number | null
  • absolute: A boolean indicating whether the orientation values are absolute.

    • Type: boolean
  • error: Any potential errors encountered during device orientation.

    • Type: Error

useFullScreen

This React hook manages the fullscreen state of an element. It returns an object containing the current fullscreen state and a function to toggle fullscreen.

Use Cases

  1. Media Players: Implement fullscreen functionality for video or audio players.

  2. Interactive Presentations: Allow users to view content in fullscreen mode for presentations.

  3. Gaming: Enable fullscreen mode for an immersive gaming experience.

Example

  import React from 'react';
  import { useFullScreen } from 'usehook-react';

  function FullScreenComponent() {
      const { isFullscreen, toggleFullscreen } = useFullScreen({
          onRequestFullscreen: () => {
              console.log('Entered fullscreen mode');
          },
          onExitFullscreen: () => {
              console.log('Exited fullscreen mode');
          },
      });

      return (
          <div>
              <button onClick={toggleFullscreen}>
                  {isFullscreen ? 'Exit Fullscreen' : 'Enter Fullscreen'}
              </button>
          </div>
      );
  }

Code Breakdown

Parameters

  • options (optional): An object with optional callback functions for requesting and exiting fullscreen.

    • Type: FullscreenOptions
  • onRequestFullscreen: Callback function to execute when entering fullscreen.

    • Type: () => void
  • onExitFullscreen: Callback function to execute when exiting fullscreen.

    • Type: () => void

Return Value

An object with the following properties and methods:

  • isFullscreen: A boolean indicating whether the element is currently in fullscreen mode.

    • Type: boolean
  • toggleFullscreen: Function to toggle the fullscreen state of the element.

    • Type: () => void

useDocumentTitle

This React hook dynamically sets the document title. It takes a title parameter and updates the document title accordingly. Optionally, you can reset the title on component unmount.

Use Cases

  1. Dynamic Page Titles: Change the document title based on dynamic content or user interactions.

  2. Single Page Applications (SPAs): Update the title as the user navigates through different sections.

  3. Accessibility: Provide meaningful and context-aware titles for improved accessibility.

Example

  import React from 'react';
  import { useDocumentTitle } from 'usehook-react';

  function DynamicTitleComponent() {
      useDocumentTitle('Dynamic Page Title');

      return (
          <div>
              {/* Your component JSX */}
          </div>
      );
  }

Code Breakdown

Parameters

  • title: The title to set for the document.
    • Type: string

Return Value

  • None (void)

useIsLoading

This React hook is designed to track loading state with an optional delay before setting it to true. It provides functions to start and stop loading.

Use Cases

  1. Asynchronous Operations: Track the loading state while waiting for data from an API or performing other asynchronous operations.

  2. User Feedback: Indicate to users that some operation is in progress, and optionally introduce a delay before showing the loading state.

  3. UI Transitions: Delay the loading state to allow smooth transitions or animations.

Example

  import React from 'react';
  import { useIsLoading } from 'usehook-react';

  function LoadingComponent() {
      const { isLoading, startLoading, stopLoading } = useIsLoading({ delay: 1000 });

      const handleButtonClick = () => {
          startLoading();

          // Simulate an asynchronous operation
          setTimeout(() => {
              stopLoading();
          }, 2000);
      };

      return (
          <div>
              <button onClick={handleButtonClick}>Start Loading</button>
              {isLoading && <p>Loading...</p>}
          </div>
      );
  }

Code Breakdown

Parameters

  • options (optional): An object with an optional delay property (in milliseconds) to delay setting loading to true.
    • Type: IsLoadingOptions

Return Value

An object with the following properties and methods:

  • isLoading: The current loading state.

    • Type: boolean
  • startLoading: Function to start loading. If a delay is specified, it will wait for the delay before setting loading to true.

    • Type: () => void
  • stopLoading: Function to stop loading.

    • Type: () => void

useParams

This React hook is a custom utility for extracting and managing custom parameters from the URL. It returns an object containing the custom parameters.

Use Cases

  1. URL Query Parameters: Extract and use custom parameters from the URL to dynamically influence component behavior.

  2. Routing: Use parameters in URL routing to navigate between different views or sections of an application.

  3. User Preferences: Adjust the behavior or appearance of a component based on custom parameters passed in the URL.

Example

  import React from 'react';
  import { useParams } from 'usehook-react';

  function CustomParamsComponent() {
      const customParams = useParams();

      return (
          <div>
              <h2>Custom Parameters</h2>
              <pre>{JSON.stringify(customParams, null, 2)}</pre>
          </div>
      );
  }

Code Breakdown

Parameters

  • None

Return Value

An object containing custom parameters extracted from the current URL.

Type: CustomParams

useScript

This React hook provides a mechanism to dynamically load scripts into the document. It takes an object with script loading options and returns a boolean indicating whether the script has been successfully loaded.

Use Cases

  1. Dynamic Script Loading: Load scripts into the document based on certain conditions or events in your React application.

  2. Third-Party Integrations: Dynamically load scripts required for third-party integrations, such as analytics, chat widgets, etc.

  3. Conditional Dependencies: Load scripts conditionally depending on the user's actions or the state of the application.

Example

  import React from 'react';
  import { useScript } from 'usehook-react';

  function ScriptLoaderComponent() {
      const isScriptLoaded = useScript({
          src: 'https://example.com/script.js',
          async: true,
          defer: true,
      });

      return (
          <div>
              <h2>Script Loaded: {isScriptLoaded ? 'Yes' : 'No'}</h2>
          </div>
      );
  }

Code Breakdown

Parameters

  • options: An object with script loading options.
    • src (string): The source URL of the script.
    • async (boolean, optional): Whether to load the script asynchronously. Default is false.
    • defer (boolean, optional): Whether to defer the script execution. Default is false.

Return Value

A boolean indicating whether the script has been successfully loaded.

useCss

This React hook provides a mechanism to dynamically load stylesheets into the document. It takes an object with stylesheet loading options and returns a boolean indicating whether the stylesheet has been successfully loaded.

Use Cases

  1. Dynamic Stylesheet Loading: Load stylesheets into the document based on certain conditions or events in your React application.

  2. Conditional Styling: Load stylesheets conditionally depending on the user's actions or the state of the application.

  3. Third-Party Styles: Dynamically load stylesheets required for third-party components or integrations.

Example

  import React from 'react';
  import { useCss } from 'usehook-react';

  function StylesheetLoaderComponent() {
      const isCssLoaded = useCss({
          href: 'https://example.com/styles.css',
      });

      return (
          <div>
              <h2>Stylesheet Loaded: {isCssLoaded ? 'Yes' : 'No'}</h2>
          </div>
      );
  }

Code Breakdown

Parameters

  • options: An object with stylesheet loading options.
    • href (string): The source URL of the stylesheet.

Return Value

A boolean indicating whether the stylesheet has been successfully loaded.

useInput

This React hook manages state for a single input or select field. It takes an object with optional configuration options and returns an object containing the input value and event handlers.

Use Cases

  1. Form Input State Management: Manage the state of form input fields with ease.

  2. Controlled Components: Implement controlled components effortlessly by using this hook for input or select fields.

  3. Dynamic Input Handling: Easily handle dynamic input changes with the provided event handlers.

Example

  import React from 'react';
  import { useInput } from 'usehook-react';

  function InputComponent() {
      const { value, onChange } = useInput({ initialValue: 'Default' });

      return (
          <div>
              <label htmlFor="inputField">Input:</label>
              <input
                  type="text"
                  id="inputField"
                  value={value}
                  onChange={onChange}
              />
              <p>Current Value: {value}</p>
          </div>
      );
  }

Code Breakdown

Parameters

  • options (optional): An object with optional configuration options.
    • initialValue (string): The initial value for the input field.

Return Value

An object containing:

  • value (string): The current value of the input field.
  • onChange (function): The event handler for input changes.

useDebouncedEffect

This React hook provides a debounced effect, allowing you to delay the execution of a function. It takes an object with the effect function, delay duration, and dependency array as parameters.

Use Cases

  1. API Requests: Delay triggering API requests until a user has stopped typing.

  2. Expensive Computations: Debounce expensive computations to avoid performance issues.

  3. Responsive UI: Delay UI updates to prevent flickering during rapid state changes.

Example

  import React, { useState } from 'react';
  import { useDebouncedEffect } from 'usehook-react';

  function DebouncedEffectComponent() {
      const [searchTerm, setSearchTerm] = useState('');

      // Assume an API search function
      const searchFunction = (term) => {
          // Perform the search
          console.log(`Searching for: ${term}`);
      };

      // Debounced effect to trigger searchFunction after a delay
      useDebouncedEffect({
          effect: () => searchFunction(searchTerm),
          delay: 500,
          dependencies: [searchTerm],
      });

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

      return (
          <div>
              <label htmlFor="searchInput">Search:</label>
              <input
                  type="text"
                  id="searchInput"
                  value={searchTerm}
                  onChange={handleInputChange}
              />
          </div>
      );
  }

Code Breakdown

Parameters

  • effect (function): The function to be executed after the specified delay.

    • Type: () => void
  • delay (number): The delay duration in milliseconds.

    • Type: number
  • dependencies (array): An array of dependencies to trigger the effect when they change.

    • Type: any[]

Return Value

This hook does not return a value; it is used for its side effect of executing the debounced effect.

useIntersectionObserver

This React hook provides a way to observe the intersection of an element with another element or the viewport. It takes an object with the target element's RefObject and optional options for the IntersectionObserver.

Use Cases

  1. Lazy Loading: Load images or content only when they come into the viewport.

  2. Infinite Scrolling: Trigger data fetching when a certain element enters the viewport.

  3. Animations: Start animations when an element becomes visible.

Example

  import React, { useRef } from 'react';
  import { useIntersectionObserver } from 'usehook-react';

  function IntersectionObserverComponent() {
      const targetRef = useRef(null);

      // Observe the intersection of the target element
      const { isIntersecting } = useIntersectionObserver({
          target: targetRef,
          options: {
              threshold: 0.5, // Trigger when 50% of the target is visible
          },
      });

      return (
          <div>
              <div
                  ref={targetRef}
                  style={{
                      height: '200px',
                      border: '1px solid #ccc',
                      overflow: 'hidden',
                      margin: '10px 0',
                  }}
              >
                  {/* Content */}
              </div>
              {isIntersecting && (
                  <p>
                      This content is now visible in the viewport! Load or animate here.
                  </p>
              )}
          </div>
      );
  }

Code Breakdown

Parameters

  • target (RefObject<Element>): A RefObject pointing to the element to be observed.

    • Type: RefObject<Element>
  • options (IntersectionObserverInit): Optional IntersectionObserver options.

    • Type: IntersectionObserverInit

Return Value

An object with the following property:

  • isIntersecting (boolean): Indicates whether the target element is intersecting with the observed element or viewport.
    • Type: boolean
0.0.3

4 months ago

0.0.2

4 months ago

0.0.1

4 months ago