https://github.com/halvaradop/hooks
https://github.com/halvaradop/hooks
Last synced: 6 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/halvaradop/hooks
- Owner: halvaradop
- License: mit
- Created: 2025-06-20T03:00:19.000Z (7 months ago)
- Default Branch: master
- Last Pushed: 2025-07-12T16:59:45.000Z (6 months ago)
- Last Synced: 2025-07-19T10:49:39.325Z (6 months ago)
- Language: TypeScript
- Size: 62.5 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @halvaradop/hooks
[](https://badge.fury.io/js/@halvaradop%2Fhooks)
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
A comprehensive collection of reusable React hooks designed to simplify common patterns and enhance your development experience. Built with TypeScript for excellent developer experience and type safety.
## Table of Contents
- [Installation](#installation)
- [Available Hooks](#available-hooks)
- [Usage Examples](#usage-examples)
- [Contributing](#contributing)
- [Code of Conduct](#code-of-conduct)
## Installation
```bash
# npm
npm install @halvaradop/hooks
# yarn
yarn add @halvaradop/hooks
# pnpm
pnpm add @halvaradop/hooks
```
## Available Hooks
### State Management
- [`useLocalStorage`](#uselocalstorage) - Sync state with localStorage
- [`useSessionStorage`](#usesessionstorage) - Sync state with sessionStorage
- [`useToggle`](#usetoggle) - Boolean state toggle functionality
### Event Handling
- [`useEventListener`](#useeventlistener) - Add event listeners to any element
- [`useDocumentEventListener`](#usedocumenteventlistener) - Listen to document events
- [`useWindowEventListener`](#usewindoweventlistener) - Listen to window events
- [`useOnClickOutside`](#useonclickoutside) - Detect clicks outside an element
### Browser APIs
- [`useBroadcastChannel`](#usebroadcastchannel) - Cross-tab communication
- [`useCopyToClipboard`](#usecopytoclipboard) - Copy text to clipboard
- [`useOnlineStatus`](#useonlinestatus) - Monitor network connectivity
- [`useMediaQuery`](#usemediaquery) - Responsive design helper
- [`useWindowSize`](#usewindowsize) - Track window dimensions
### Timing
- [`useInterval`](#useinterval) - Declarative intervals
## Usage Examples
### useLocalStorage
Synchronize state with localStorage, with automatic serialization and cross-tab synchronization.
```tsx
import { useLocalStorage } from "@halvaradop/hooks"
function Settings() {
const [theme, setTheme, removeTheme] = useLocalStorage("theme", "light", {
withEvent: true, // Sync across tabs
})
return (
Current theme: {theme}
setTheme("dark")}>Dark Mode
setTheme("light")}>Light Mode
Reset
)
}
```
### useSessionStorage
Synchronize state with sessionStorage, similar to localStorage but session-scoped.
```tsx
import { useSessionStorage } from "@halvaradop/hooks"
function SessionSettings() {
const [settings, setSettings, removeSettings] = useSessionStorage("session-settings", {
theme: "auto",
language: "en",
})
return (
Current settings: {JSON.stringify(settings)}
setSettings({ ...settings, theme: "dark" })}>Dark Theme
Clear Session
)
}
```
### useDocumentEventListener
Listen to document events with automatic cleanup.
```tsx
import { useDocumentEventListener } from "@halvaradop/hooks"
function GlobalShortcuts() {
useDocumentEventListener("keydown", (event) => {
if (event.ctrlKey && event.key === "k") {
event.preventDefault()
openCommandPalette()
}
})
useDocumentEventListener("click", (event) => {
console.log("Document clicked at:", event.clientX, event.clientY)
})
return
Global shortcuts are active!
}
```
### useWindowEventListener
Listen to window events like resize, focus, etc.
```tsx
import { useWindowEventListener } from "@halvaradop/hooks"
function WindowEvents() {
useWindowEventListener("resize", () => {
console.log("Window resized to:", window.innerWidth, window.innerHeight)
})
useWindowEventListener("focus", () => {
console.log("Window gained focus")
})
useWindowEventListener("blur", () => {
console.log("Window lost focus")
})
return
Window event listeners are active!
}
```
### useOnClickOutside
Detect clicks outside a specific element.
```tsx
import { useOnClickOutside } from "@halvaradop/hooks"
import { useRef, useState } from "react"
function DropdownMenu() {
const [isOpen, setIsOpen] = useState(false)
const dropdownRef = useRef(null)
useOnClickOutside(dropdownRef, () => {
setIsOpen(false)
})
return (
setIsOpen(!isOpen)}>Toggle Menu
{isOpen && (
Click outside to close
Menu Item 1
Menu Item 2
)}
)
}
```
### useCopyToClipboard
Copy text to clipboard with success/error handling.
```tsx
import { useCopyToClipboard } from "@halvaradop/hooks"
function CopyButton() {
const [copiedText, copyToClipboard] = useCopyToClipboard()
const handleCopy = async () => {
const success = await copyToClipboard("Hello, World!")
if (success) {
console.log("Text copied successfully!")
} else {
console.error("Failed to copy text")
}
}
return (
Copy Text
{copiedText && Last copied: {copiedText}
}
)
}
```
### useWindowSize
Track window dimensions with automatic updates on resize.
```tsx
import { useWindowSize } from "@halvaradop/hooks"
function WindowInfo() {
const { width, height } = useWindowSize()
return (
Window size: {width} x {height}
Aspect ratio: {(width / height).toFixed(2)}
{width < 768 && Mobile view
}
{width >= 768 && width < 1024 && Tablet view
}
{width >= 1024 && Desktop view
}
)
}
```
### useInterval
Set up intervals with automatic cleanup.
```tsx
import { useInterval } from "@halvaradop/hooks"
import { useState } from "react"
function Timer() {
const [count, setCount] = useState(0)
const [isRunning, setIsRunning] = useState(true)
useInterval(
() => {
setCount(count + 1)
},
isRunning ? 1000 : null,
) // Pass null to pause
return (
Count: {count}
setIsRunning(!isRunning)}>{isRunning ? "Pause" : "Start"}
setCount(0)}>Reset
)
}
```
### useEventListener
Add event listeners with automatic cleanup and TypeScript support.
```tsx
import { useEventListener } from "@halvaradop/hooks"
import { useRef } from "react"
function KeyboardHandler() {
const buttonRef = useRef(null)
// Global keyboard listener
useEventListener(document, "keydown", (event) => {
if (event.ctrlKey && event.key === "s") {
event.preventDefault()
console.log("Save shortcut pressed!")
}
})
// Element-specific listener
useEventListener(buttonRef, "click", () => {
console.log("Button clicked!")
})
return Click me
}
```
### useMediaQuery
Create responsive components with CSS media queries.
```tsx
import { useMediaQuery } from "@halvaradop/hooks"
function ResponsiveComponent() {
const isMobile = useMediaQuery("(max-width: 768px)")
const isTablet = useMediaQuery("(min-width: 769px) and (max-width: 1024px)")
const isDesktop = useMediaQuery("(min-width: 1025px)")
return (
{isMobile && }
{isTablet && }
{isDesktop && }
)
}
```
### useBroadcastChannel
Communicate between tabs/windows using the BroadcastChannel API.
```tsx
import { useBroadcastChannel } from "@halvaradop/hooks"
function CrossTabChat() {
const [message, sendMessage, closeChannel, isSupported] = useBroadcastChannel("chat-channel")
const handleSendMessage = () => {
sendMessage({ text: "Hello from this tab!", timestamp: Date.now() })
}
return (
{isSupported ? (
<>
Last message: {message?.text}
Send Message
Close Channel
>
) : (
BroadcastChannel not supported
)}
)
}
```
### useOnlineStatus
Monitor network connectivity status.
```tsx
import { useOnlineStatus } from "@halvaradop/hooks"
function NetworkStatus() {
const isOnline = useOnlineStatus()
return
{isOnline ? "🟢 Online" : "🔴 Offline"}
}
```
### useToggle
Manage boolean state with toggle functionality.
```tsx
import { useToggle } from "@halvaradop/hooks"
function ToggleExample() {
const [isVisible, toggleVisible] = useToggle(false)
return (
toggleVisible()}>{isVisible ? "Hide" : "Show"} Content
{isVisible && This content is toggleable!
}
)
}
```
## Contributing
We welcome contributions to `@halvaradop/hooks`! If you have an idea for a new type or find an improvement to an existing one, please feel free to open an issue or create a pull request. We offer a guide on how to contribute to the project and the necessary steps to do so. Here's how you can contribute, Read our [Contribuing Guideline](https://github.com/halvaradop/.github/blob/master/.github/CONTRIBUTING.md).
## Code of conduct
Please be aware that this project has a code of conduct, and we expect all contributors to follow these guidelines in their interactions. For more information, please read our [Code of Conduct](https://github.com/halvaradop/.github/blob/master/.github/CODE_OF_CONDUCT.md).