usehook-react
v0.0.3
Published
Supercharge your React development with a collection of custom hooks designed for speed and efficiency. Elevate your application development experience with these purpose-built React hooks, crafted to simplify complex tasks and accelerate your workflow.
Downloads
2
Maintainers
Readme
React custom hooks for faster development.
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
anduseSessionStorage
: 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
- useFetchWithRetry
- usePageVisibility
- useThrottle
- usetoggle
- useDebounce
- useCopyUrl
- useWindowSize
- useWriteToClipboard
- useReadFromClipboard
- usePrevious
- useMediaQuery
- useFetch
- useAsync
- useInterval
- useOnClickOutside
- useKeyPress
- useLocalStorage
- useSessionStorage
- useScroll
- useHover
- useAnimationFrame
- useClipboard
- useOnlineStatus
- useIdle
- useHistory
- useCookie
- useMeasure
- useGeoLocation
- useDeviceOrientation
- useFullScreen
- useDocumentTitle
- useIsLoading
- useParams
- useScript
- useCss
- useForm
- useInput
- useDebouncedEffect
- useIntersectionObserver
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:
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.
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.
Tracking User Engagement:
- Track how long users are actually viewing your content by measuring the time the page is visible.
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:
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.
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.
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
- Type:
delay
: The delay (in milliseconds) between consecutive invocations of the throttled callback.- Type:
number
- Type:
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:
Toggle UI Elements:
- Toggle the visibility or state of UI elements in response to user interactions.
Control Conditional Rendering:
- Conditionally render components based on the toggled boolean value.
Form Input Handling:
- Manage the state of checkboxes or toggle switches in forms.
Toggle Between Two States:
- Easily toggle between
true
andfalse
states with convenient functions.
- Easily toggle between
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 tofalse
.- Type:
boolean
- Type:
Return Value
ToggleResult
: An object containing the following properties and functions:value
: The current boolean value.- Type:
boolean
- Type:
toggle
: A function to toggle the boolean value.- Type:
() => void
- Type:
setTrue
: A function to set the boolean value totrue
.- Type:
() => void
- Type:
setFalse
: A function to set the boolean value tofalse
.- Type:
() => void
- Type:
toggleWithCallback
: A function to toggle the boolean value with an optional callback, which receives the updated boolean value.- Type:
(callback?: (value: boolean) => void) => void
- Type:
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
- Type:
delay
: The delay (in milliseconds) before updating the debounced value.- Type:
number
- Type:
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:
Shareable Links:
- Enable users to quickly copy the URL of the current page for sharing.
Save URL to Clipboard:
- Implement a "Copy Link" button to allow users to copy the current page's URL for later use.
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:
Responsive UI Elements:
- Dynamically adjust the size or layout of UI elements based on the window size.
Media Queries:
- Create custom media queries in your components by utilizing the window size information.
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
- Type:
height
: The current height of the browser window.- Type:
number
- Type:
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:
Copy-to-Clipboard Buttons:
- Implement buttons that allow users to copy certain text to the clipboard.
Feedback for Copy Operations:
- Provide visual feedback to users indicating whether the copy operation was successful.
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
- Type:
writeToClipboard
: A function to write the provided text to the clipboard.- Type:
(text: string) => void
- Type:
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:
Paste Operations:
- Implement components that allow users to paste text from the clipboard.
Interactive UI Components:
- Integrate with UI components to display or manipulate text read from the clipboard.
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 ornull
if the operation failed.- Type:
string | null
- Type:
readFromClipboard
: A function to trigger the read operation from the clipboard.- Type:
() => void
- Type:
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
- Type:
Return Value
- The previous value.
- Type:
T | undefined
- Type:
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
- Type:
Return Value
- Whether the media query currently matches.
- Type:
boolean
- Type:
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
- Type:
options
: Optional request options for the fetch operation.- Type:
RequestInit | undefined
- Type:
initialData
: Initial data to set before fetching.- Type:
T | undefined
- Type:
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>
- Type:
immediate
: Optional flag to determine whether to run the asynchronous function immediately.- Type:
boolean
- Default:
true
- Type:
Return Value
- An object with the following properties:
data
: The data obtained from the asynchronous operation ornull
.- Type:
T | null
- Type:
loading
: A boolean indicating whether the asynchronous operation is in progress.- Type:
boolean
- Type:
error
: An error object if the asynchronous operation encounters an error, otherwisenull
.- Type:
Error | null
- Type:
run
: A function to manually trigger the asynchronous operation.- Type:
() => void
- Type:
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
- Type:
delay
: The interval duration in milliseconds. Passnull
to stop the interval.- Type:
number | null
- Type:
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>
- Type:
callback
: Callback function to be executed when a click outside occurs.- Type:
(event: MouseEvent) => void
- Type:
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
- Type:
callback
: Callback function to be executed when the specified key is pressed.- Type:
() => void
- Type:
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
- Type:
initialState
: The initial state value.- Type:
T
- Type:
Return Value
A tuple containing:
state
: The current state value.- Type:
T
- Type:
setState
: A function to update the state.- Type:
Dispatch<SetStateAction<T>>
- Type:
removeFromLocalStorage
: A function to remove the stored data from local storage.- Type:
() => void
- Type:
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
- Type:
initialState
: The initial state value.- Type:
T
- Type:
Return Value
A tuple containing:
state
: The current state value.- Type:
T
- Type:
setState
: A function to update the state.- Type:
Dispatch<SetStateAction<T>>
- Type:
removeFromSessionStorage
: A function to remove the stored data from session storage.- Type:
() => void
- Type:
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
Custom Animations or Effects: You can trigger animations or effects based on the scroll position, creating a dynamic and engaging user experience.
Sticky Navigation: Implement sticky navigation bars that appear or disappear based on the user's scroll behavior.
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
- Type:
y
: The vertical scroll position.- Type:
number
- Type:
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
Conditional Rendering: Show or hide certain elements based on whether they are being hovered over.
Styling Changes: Apply different styles to an element when it is being hovered, providing visual feedback to users.
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
Smooth Animations: Use this hook to create smooth and efficient animations by updating the state or manipulating the DOM on each animation frame.
Game Development: Implement game-related logic that requires constant updates and calculations on each animation frame.
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
- Type:
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
Copy-Paste Operations: Utilize the hook to facilitate copy-paste functionality in your application.
Clipboard Management: Keep track of the clipboard content within your components.
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
- Type:
writeToClipboard
: A function to write to the clipboard.- Type:
(text: string) => void
- Type:
readFromClipboard
: A function to read from the clipboard.- Type:
() => void
- Type:
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
Network Status Display: Display network connectivity status in your application UI.
Conditional Rendering: Conditionally render components or features based on the device's online status.
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
Automated Logout: Log out users automatically when they remain idle for a specific period.
Energy Saving: Implement features that reduce energy consumption or turn off certain animations when the user is idle.
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 optionaltimeout
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
Programmatic Navigation: Navigate between different views or pages in a React application based on user actions or application logic.
History Control: Implement custom controls for navigating backward or forward in the user's history.
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
User Authentication: Manage authentication tokens or session data stored in cookies.
Persistent User Preferences: Store user preferences or settings in cookies for a personalized experience.
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
- Type:
options
(optional): An object with optional configuration options for the cookie.- Type:
CookieOptions
- Type:
Return Value
An object with the following properties and methods:
value
: The current cookie value.- Type:
string | null
- Type:
updateCookie
: Function to update the cookie with a new value and optional options.- Type:
(newValue: string, options?: CookieOptions) => void
- Type:
deleteCookie
: Function to delete the cookie.- Type:
() => void
- Type:
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
Responsive Design: Adapt the layout or styles based on the dimensions of a specific element.
Dynamic Components: Dynamically adjust components based on the size of their container.
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>
- Type:
dimensions
: The dimensions of the measured element.- Type:
DOMRectReadOnly | null
- Type:
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
Location-Based Features: Customize your application based on the user's current location.
Mapping and Navigation: Implement maps or navigation features by utilizing real-time geolocation.
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
- Type:
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
- Type:
error
: Any potential errors encountered during geolocation.- Type:
Error
- Type:
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
Augmented Reality: Develop augmented reality (AR) experiences by tracking the device's orientation.
Gaming: Create games that respond to the user's device movements.
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
- Type:
beta
: The rotation around the x-axis.- Type:
number | null
- Type:
gamma
: The rotation around the y-axis.- Type:
number | null
- Type:
absolute
: A boolean indicating whether the orientation values are absolute.- Type:
boolean
- Type:
error
: Any potential errors encountered during device orientation.- Type:
Error
- Type:
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
Media Players: Implement fullscreen functionality for video or audio players.
Interactive Presentations: Allow users to view content in fullscreen mode for presentations.
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
- Type:
onRequestFullscreen
: Callback function to execute when entering fullscreen.- Type:
() => void
- Type:
onExitFullscreen
: Callback function to execute when exiting fullscreen.- Type:
() => void
- Type:
Return Value
An object with the following properties and methods:
isFullscreen
: A boolean indicating whether the element is currently in fullscreen mode.- Type:
boolean
- Type:
toggleFullscreen
: Function to toggle the fullscreen state of the element.- Type:
() => void
- Type:
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
Dynamic Page Titles: Change the document title based on dynamic content or user interactions.
Single Page Applications (SPAs): Update the title as the user navigates through different sections.
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
- Type:
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
Asynchronous Operations: Track the loading state while waiting for data from an API or performing other asynchronous operations.
User Feedback: Indicate to users that some operation is in progress, and optionally introduce a delay before showing the loading state.
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 optionaldelay
property (in milliseconds) to delay setting loading to true.- Type:
IsLoadingOptions
- Type:
Return Value
An object with the following properties and methods:
isLoading
: The current loading state.- Type:
boolean
- Type:
startLoading
: Function to start loading. If a delay is specified, it will wait for the delay before setting loading to true.- Type:
() => void
- Type:
stopLoading
: Function to stop loading.- Type:
() => void
- Type:
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
URL Query Parameters: Extract and use custom parameters from the URL to dynamically influence component behavior.
Routing: Use parameters in URL routing to navigate between different views or sections of an application.
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
Dynamic Script Loading: Load scripts into the document based on certain conditions or events in your React application.
Third-Party Integrations: Dynamically load scripts required for third-party integrations, such as analytics, chat widgets, etc.
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
Dynamic Stylesheet Loading: Load stylesheets into the document based on certain conditions or events in your React application.
Conditional Styling: Load stylesheets conditionally depending on the user's actions or the state of the application.
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
Form Input State Management: Manage the state of form input fields with ease.
Controlled Components: Implement controlled components effortlessly by using this hook for input or select fields.
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
API Requests: Delay triggering API requests until a user has stopped typing.
Expensive Computations: Debounce expensive computations to avoid performance issues.
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
- Type:
delay
(number): The delay duration in milliseconds.- Type:
number
- Type:
dependencies
(array): An array of dependencies to trigger the effect when they change.- Type:
any[]
- Type:
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
Lazy Loading: Load images or content only when they come into the viewport.
Infinite Scrolling: Trigger data fetching when a certain element enters the viewport.
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>
): ARefObject
pointing to the element to be observed.- Type:
RefObject<Element>
- Type:
options
(IntersectionObserverInit
): OptionalIntersectionObserver
options.- Type:
IntersectionObserverInit
- Type:
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
- Type: