reactuse

website·Indexed 32 days ago

https://reactuse.org/

A collection of React hooks and helper functions for browser APIs, async state management, and utility tasks. Includes hooks for geolocation, clipboard, media controls, and file system access, as well as helpers for state management and class name normalization.

Tokens
124.6K
Snippets
843
Records
933
Agent score
59%

What's inside reactuse

  1. Track network status with useNetwork

    The useNetwork hook monitors the device's network connectivity and provides detailed information about the connection quality and type. It listens for online, offline, and change events on the window and navigator connection objects to provide real-time updates.
    import { useNetwork } from '@siberiacancode/reactuse';
    
    const MyComponent = () => {
      const { online, downlink, effectiveType, rtt, type } = useNetwork();
    
      return (
        <div>
          <p>Status: {online ? 'Online' : 'Offline'}</p>
          {online && <p>Connection Type: {type}</p>}
          {online && <p>Effective Speed: {effectiveType}</p>}
        </div>
      );
    };
  2. Manage a numeric counter with useCounter

    The useCounter hook manages a numeric state with built-in methods for incrementing, decrementing, resetting, and setting the value. It supports optional min and max constraints to prevent the counter from exceeding specific bounds.
    import { useCounter } from '@siberiacancode/reactuse';
    
    const Demo = () => {
      // Initialize with value 2, min 1, and max 10
      const counter = useCounter(2, { min: 1, max: 10 });
    
      return (
        <div>
          <p>Current Value: {counter.value}</p>
          <button onClick={() => counter.dec()}>Decrement</button>
          <button onClick={() => counter.inc()}>Increment</button>
          <button onClick={() => counter.reset()}>Reset</button>
        </div>
      );
    };
  3. Create a type-safe event emitter with createEventEmitter

    The createEventEmitter helper function is used to create a type-safe event emitter. This allows you to define specific event names and their associated payload types, ensuring type safety when emitting and listening for events across your application.
  4. Manage reactive URL query parameters with useUrlSearchParams

    The useUrlSearchParams hook allows you to manage URL search parameters reactively. It synchronizes a state object with the browser's URL query string, making it ideal for implementing shareable filters, search queries, or pagination where the state must persist across page refreshes or be shareable via a link.
    import { useUrlSearchParams } from '@siberiacancode/reactuse';
    
    interface Filters {
      cuisine: string;
      search: string;
    }
    
    const Demo = () => {
      // Initialize with default values
      const filters = useUrlSearchParams<Filters>({
        search: '',
        cuisine: 'All'
      });
    
      // Access current values via filters.value
      const { cuisine } = filters.value;
      const search = String(filters.value.search ?? '');
    
      return (
        <input
          value={search}
          onChange={(event) => filters.set({ search: event.target.value })}
        />
      );
    };
  5. Track swipe gestures with useSwipe

    The useSwipe hook monitors swipe gestures on a specific DOM element. It supports both PointerEvents and TouchEvents. It can be used by passing a ref to a target element or by using the returned ref to attach to an element. The hook provides the current swipe direction, the horizontal/vertical length of the swipe, and a boolean indicating if a swipe is currently active.
  6. Manage state toggles with useToggle

    The useToggle hook creates a state toggle that cycles through a provided list of values. By default, it toggles between false and true. If a custom array of values is provided, calling the toggle function without arguments will cycle to the next value in the sequence.
    // Default boolean toggle
    const [on, toggle] = useToggle();
    
    // Custom multi-value toggle
    const [value, toggle] = useToggle(['light', 'dark', 'system'] as const);
  7. Manage audio playback with useAudio

    The useAudio hook manages audio playback in the browser. It supports basic playback controls and audio sprite support. It can be configured with options such as interrupt (to stop current playback when starting a new one) and volume levels.
    import { useAudio } from '@siberiacancode/reactuse';
    
    const audio = useAudio('/sounds/pop-down.mp3', {
      interrupt: true,
      volume: 0.6
    });
    
    // To play the sound
    audio.play();
    
    // To stop the sound
    audio.stop();
  8. Manage controlled and uncontrolled state with useControllableState

    The useControllableState hook allows a component to be used in two ways: as a controlled component (where the value is passed as a prop) or as an uncontrolled component (where it manages its own state starting from an initial value).

    If value is provided in the options, the hook operates in controlled mode. Otherwise, it uses initialValue to maintain internal state.

    const [value, setValue, isControlled] = useControllableState({ 
      initialValue: 'initial' 
    });
  9. Monitor and control element scrolling with useScroll

    The useScroll hook allows you to track the scroll position, direction, and boundary status (arrived at top/bottom/left/right) of a target element or the global window. It provides methods to programmatically scroll the element and a snapshot of the current scroll state.
  10. Manage form field state with useField

    The useField hook manages the state of a single form field, including its value, validation errors, and interaction states (dirty/touched). It provides a register function that returns the necessary props (ref, onChange, onBlur) to be spread onto an HTML input, select, or textarea element.
    import { useField } from 'react-use';
    
    const MyComponent = () => {
      const { register, getValue, error, touched } = useField('initial value');
      const { ref, onChange, onBlur } = register();
    
      return (
        <div>
          <input ref={ref} onChange={onChange} onBlur={onBlur} />
          {touched && error && <span>{error}</span>}
        </div>
      );
    };
  11. Get current geolocation with useGeolocation

    The useGeolocation hook tracks and returns the current geolocation state of the browser. It provides the latitude and longitude of the user, along with loading and error states to handle the asynchronous nature of the Geolocation API.
    import { useGeolocation } from '@siberiacancode/reactuse';
    
    const Demo = () => {
      const geolocation = useGeolocation();
    
      // Access geolocation data via geolocation.value
      const { latitude, longitude, loading, error } = geolocation.value;
    
      if (loading) return <div>Locating...</div>;
      if (error) return <div>Location unavailable</div>;
    
      return (
        <div>
          Latitude: {latitude}
          Longitude: {longitude}
        </div>
      );
    };