React Fast Hooks

website·Indexed 30 days ago

https://jpranays.github.io/react-fast-hooks

A performance-optimized library of React hooks for common tasks, including browser API management (cookies, localStorage, clipboard, notifications), DOM interactions (intersection observer, mutation observer, scroll position, window size), and device features (battery status, vibration, device orientation).

Tokens
13K
Snippets
77
Records
104
Agent score
73%

What's inside React Fast Hooks

  1. Core features of react-fast-hooks

    react-fast-hooks is a utility library designed for high performance and minimal bundle size. Key technical characteristics include:

    • SSR-Friendly: Fully compatible with Server-Side Rendering, specifically optimized for frameworks like Next.js.
    • TypeScript Support: Includes comprehensive type definitions for type-safe development.
    • Tree Shaking: Optimized to ensure only the hooks actually used in the application are included in the final production bundle.
    • Cross-Browser Compatibility: Maintains consistent behavior across all major web browsers.
  2. Get device battery status with useBattery

    The useBattery hook allows you to track the current battery status of a device. It provides real-time information about the battery level, whether the device is charging, and the estimated time until the battery is fully charged or discharged. It also includes flags to check if the Battery API is supported by the browser and if the data is still loading.
    function App() {
    	const batteryState = useBattery();
    
    	return (
    		<div
    >
    			{batteryState.loading ? (
    				<p>Loading battery status...</p>
    			) : !batteryState.supported ? (
    				<p>Battery API not supported on this device.</p>
    			) : (
    				<div>
    					<p>Battery Level: {batteryState.level * 100}%</p>
    					<p>Charging: {batteryState.charging ? "Yes" : "No"}</p>
    					<p>Charging Time: {batteryState.chargingTime} seconds</p>
    					<p>Discharging Time: {batteryState.dischargingTime} seconds</p>
    				</div>
    			)}
    		</div>
    	);
    }
  3. Manage browser history with useHistory

    The useHistory hook provides a set of utilities to programmatically navigate the browser history stack and manage associated state. It allows developers to push new paths, replace the current entry, and move backward or forward in the history.
    function App() {
    	const { push, replace, goBack, goForward, state } = useHistory();
    
    	return (
    		<div
    >
    			<button onClick={() => push("/new-path", { some: "state" })}>
    				Push State
    			</button>
    			<button onClick={() => replace("/replace-path", { some: "state" })}>
    				Replace State
    			</button>
    			<button onClick={() => goBack()}>Go Back</button>
    			<button onClick={() => goForward()}>Go Forward</button>
    			<div
    >
    				Current State: {JSON.stringify(state)}
    			</div>
    		</div>
    	);
    }
  4. Install react-fast-hooks

    react-fast-hooks is a library providing performance-optimized hooks designed to minimize re-renders. It can be installed via npm or Yarn.
    # Using npm
    npm install react-fast-hooks
    
    # Using Yarn
    yarn add react-fast-hooks
  5. Lock and unlock body scrolling with useScrollLock

    The useScrollLock hook allows you to programmatically lock and unlock scrolling on the body element. It utilizes a MutationObserver to ensure the scroll lock remains active even if other scripts attempt to modify the body's style.
    import { useScrollLock } from 'react-fast-hooks';
    
    function App() {
    	const { lockScroll, unlockScroll, isLocked } = useScrollLock();
    
    	return (
    		<div>
    			<button onClick={lockScroll}>Lock Scroll</button>
    			<button onClick={unlockScroll}>Unlock Scroll</button>
    			<p>{`Scroll is ${isLocked ? "locked" : "unlocked"}`}</p>
    		</div>
    	);
    }
  6. Detect the current system theme with useSystemTheme

    The useSystemTheme hook allows you to retrieve the current system color theme of the user's device. It returns a value of type Theme, which will be either 'light' or 'dark'.
    function App() {
    	const theme = useSystemTheme();
    
    	return (
    		<div
    		>
    			<p>Current System Theme: {theme}</p>
    		</div>
    	);
    }
  7. Detect media query matches with useMediaQuery

    The useMediaQuery hook allows you to detect if a specific CSS media query matches the current browser viewport. It takes a media query string as an argument and returns a boolean indicating whether the query currently matches.
    function App() {
    	const isMobile = useMediaQuery("(max-width: 600px)");
    	const isDesktop = useMediaQuery("(min-width: 1024px)");
    
    	return (
    		<>
    			<div>
    				<p>Mobile View : {isMobile ? "true" : "false"}</p>
    			</div>
    			<div>
    				<p>Desktop View : {isDesktop ? "true" : "false"}</p>
    			</div>
    		</>
    	);
    }
  8. Manage device vibration with useVibration

    The useVibration hook allows developers to trigger vibration patterns and stop vibrations on supported devices. It provides a boolean isSupported flag to conditionally render vibration features and an error object to handle failures during vibration attempts.
    function App() {
    	const { vibrate, stop, isSupported, error } = useVibration();
    
    	return (
    		<div
    >
    			<button onClick={() => vibrate([200, 100, 200])}>Vibrate Pattern</button>
    			<button onClick={stop}>Stop Vibration</button>
    			<p>
    				{isSupported
    					? "Vibration is supported on this device."
    					: "Vibration is not supported on this device."}
    			</p>
    			{error && <p>Error: {error.message}</p>}
    		</div>
    	);
    }
  9. Track mouse position with useMouse

    The useMouse hook tracks the mouse position relative to a specified element. It requires a React ref to the target element and returns an object containing coordinates relative to the element, the viewport, and the page.
    import React, { useRef } from 'react';
    import { useMouse } from 'react-fast-hooks';
    
    function App() {
    	const elementRef = useRef(null);
    	const { x, y, elementX, elementY, pageX, pageY } = useMouse(elementRef);
    
    	return (
    		<div
    			ref={elementRef}
    			style={{ height: "500px", border: "1px solid black" }}
    		>
    			<h1>Mouse Position</h1>
    			<p>Relative to Element - X: {x}, Y: {y}</p>
    			<p>Element X: {elementX}, Element Y: {elementY}</p>
    			<p>Page X: {pageX}, Page Y: {pageY}</p>
    		</div>
    	);
    }
  10. Get current window dimensions with useWindowSize

    The useWindowSize hook tracks and returns the current width and height of the browser window. It accepts an optional throttleTime parameter (in milliseconds) to limit the frequency of updates during window resizing, which helps optimize performance. The default throttle time is 200ms.
    import { useWindowSize } from 'react-fast-hooks';
    
    function App() {
      // Optional throttle time of 200ms
      const { width, height } = useWindowSize(200);
    
      return (
        <div>
          <p>Window Width: {width}px</p>
          <p>Window Height: {height}px</p>
        </div>
      );
    }
  11. Track browser connectivity with useOnlineStatus

    The useOnlineStatus hook provides a real-time boolean value indicating whether the browser is currently online or offline. This is useful for displaying connectivity warnings or disabling network-dependent features when the user loses internet access.
    import { useOnlineStatus } from 'react-fast-hooks';
    
    function App() {
    	const isOnline = useOnlineStatus();
    
    	return (
    		<div
    			<p>{isOnline ? "You are online" : "You are offline"}</p>
    		</div>
    	);
    }