@react-hooks-hub/use-throttle
v1.0.7
Published
This hook provide a way to control and limit the rate at which a function can be called.
Downloads
7
Maintainers
Readme
@react-hooks-hub/use-throttle
Installation
Use your preferred package manager to install @react-hooks-hub/use-throttle
:
npm install @react-hooks-hub/use-throttle
# or
yarn add @react-hooks-hub/use-throttle
Usage
Import and use the throttle hook in your component:
import React, { useState } from 'react';
import { useThrottle } from '@react-hooks-hub/use-throttle';
function CursorPositionTracker() {
const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 });
// Create a throttled version of the function to update cursor position
const updateCursorPosition = useThrottle((e) => {
setCursorPosition({ x: e.clientX, y: e.clientY });
}, 100); // Throttle to 100ms
// Attach an event listener to track cursor movement
const handleMouseMove = (e) => {
updateCursorPosition(e);
};
return (
<div>
<h1>Cursor Position Tracker</h1>
<p>Move your mouse around to see the cursor's position:</p>
<div
onMouseMove={handleMouseMove}
style={{
width: '300px',
height: '300px',
border: '1px solid #ccc',
padding: '10px',
}}
>
<p>Cursor X: {cursorPosition.x}</p>
<p>Cursor Y: {cursorPosition.y}</p>
</div>
</div>
);
}
export default CursorPositionTracker;