usereacthelpers
v2.1.1
Published
A collection of custom React hooks
Readme
React Custom Hooks
Introduction
This package provides a collection of useful React custom hooks that help manage various aspects of a React application efficiently. These hooks include online status detection, battery status monitoring, password strength checking, input validation, idle state detection, and storage management with localStorage and sessionStorage.
Installation
To install the package, run:
npm install your-package-nameor with Yarn:
yarn add your-package-nameAvailable Hooks
1. useOnlineStatus
Detects whether the user is online or offline.
Usage
import { useOnlineStatus } from "your-package-name";
function App() {
const isOnline = useOnlineStatus();
return <div>{isOnline ? "Online" : "Offline"}</div>;
}2. useToggle
A simple toggle hook.
Usage
import { useToggle } from "your-package-name";
const ToggleComponent = () => {
const [isOn, toggle] = useToggle();
return (
<div>
<p>{isOn ? "ON" : "OFF"}</p>
<button onClick={toggle}>Toggle</button>
</div>
);
};3. usePasswordStrength
Checks password strength based on length and complexity.
Usage
import { usePasswordStrength } from "your-package-name";
function PasswordInput() {
const [password, setPassword] = useState("");
const strength = usePasswordStrength(password);
return (
<div>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<p>Password Strength: {strength}</p>
</div>
);
}4. useInputValidation
Validates input based on custom validation rules.
Usage
import { useInputValidation } from "your-package-name";
function EmailInput() {
const [email, setEmail, isValid] = useInputValidation("", (value) =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
);
return (
<div>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{!isValid && <p>Invalid email format</p>}
</div>
);
}5. useIdle
Detects when the user has been idle for a specified time.
Usage
import { useIdle } from "your-package-name";
function IdleComponent() {
const isIdle = useIdle(5000); // 5 seconds
return <div>{isIdle ? "User is idle" : "Active"}</div>;
}6. useLocalStorage
Stores and retrieves values from localStorage.
Usage
import { useLocalStorage } from "your-package-name";
function App() {
const [name, setName] = useLocalStorage("name", "Guest");
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Stored Name: {name}</p>
</div>
);
}7. useSessionStorage
Stores and retrieves values from sessionStorage.
Usage
import { useSessionStorage } from "your-package-name";
function App() {
const [theme, setTheme] = useSessionStorage("theme", "light");
return (
<div>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Toggle Theme</button>
<p>Current Theme: {theme}</p>
</div>
);
}Contributing
Feel free to open issues and pull requests if you have suggestions or improvements.
License
This package is licensed under the MIT License.
