hook-conditional
Version:
Conditionally run different React hooks at runtime with a clean and safe API that follows the Rules of Hooks.
192 lines (127 loc) β’ 5.37 kB
Markdown

**Dynamic Hook Logic in React, Based on Any Runtime Condition** Simplify conditional logic in your components by delegating it to purpose-built hooks mapped to values like roles, flags, environments, or status codes.
[](https://www.npmjs.com/package/hook-conditional)
[](https://www.npmjs.com/package/hook-conditional)
[](LICENSE)
[](https://github.com/jp-coffee/hook-conditional/actions)
- π **Switch on Any Condition** β Support for strings, numbers, booleans, or any discriminant value.
- π§ **Declarative Hook Selection** β Map conditions to custom hooks and let React do the rest.
- β‘ **Fully Compliant** β All hooks are called unconditionally, following the Rules of Hooks.
- β¨ **Tiny & Typed** β Minimal, type-safe API with full IntelliSense support.
- π‘ **Optional Fallback** β Gracefully handle unmatched conditions with a fallback hook.
Install via your preferred package manager:
```sh
npm install hook-conditional
yarn add hook-conditional
pnpm add hook-conditional
bun add hook-conditional
```
```tsx
"use client";
import { useConditionalHook } from "hook-conditional";
const Page = () => {
const env = process.env.NODE_ENV;
const value = useConditionalHook(env, {
development: () => useDevHook(),
production: () => useProdHook(),
test: () => useTestHook(),
});
return <p>{value}</p>;
};
```
Switches between custom hooks based on a condition. All mapped hooks are **always executed** to comply with Reactβs Rules of Hooks, but **only the result of the matching hook is returned**.
- `condition` (`string | number | boolean`)
The runtime value that determines which hook result to return.
- `hookMap` (`Record<string | number, () => TResult>`)
An object where each key corresponds to a possible value of `condition`, and the value is a hook function to execute.
- `fallbackHook` (`() => TResult`, optional)
A fallback hook to use when no match is found in the map.
- `TResult` β The result of the matched hook (or fallback hook if no match is found).
## π Security & Provenance
This package is published with **NPM Package Provenance**, which provides cryptographic proof that the package was built from the source code in this repository using GitHub Actions.
### Verifying Package Authenticity
You can verify the package's provenance using:
```bash
# Install the package
npm install hook-conditional
# Verify the provenance
npm audit signatures
# Or use the provided verification script
npm run verify-provenance
```
### What This Means
- β
**Authentic Source**: The package was built from this exact repository
- β
**Secure Build**: Built in a trusted GitHub Actions environment
- β
**Tamper-Proof**: Cryptographically signed to prevent supply chain attacks
- β
**Transparent**: You can verify the build process and source code
For more information about NPM Package Provenance, see the [official documentation](https://docs.npmjs.com/generating-provenance-statements).
## π‘ Examples
### Role-based hook switching
```tsx
"use client";
import useConditionalHook from "hook-conditional";
const Page = () => {
const role = useUserRole();
const permissions: string[] = useConditionalHook(role, {
guest: () => useGuestPermissions(),
user: () => useUserPermissions(),
admin: () => useAdminPermissions(),
});
return <div>Permissions: {permissions.join(", ")}</div>;
};
```
```tsx
"use client";
import useConditionalHook from "hook-conditional";
const Page = () => {
const isEnabled = useFeatureFlag("new-ui");
const ui = useConditionalHook(isEnabled, {
true: () => useNewUI(),
false: () => useOldUI(),
});
return <>{ui}</>;
};
```
```tsx
"use client";
import useConditionalHook from "hook-conditional";
const Page = () => {
const status = useStatus();
const content = useConditionalHook(
status,
{
200: () => useSuccessContent(),
404: () => useNotFoundContent(),
500: () => useErrorContent(),
},
() => useDefaultContent()
);
return <>{content}</>;
};
```
Contributions are welcome! To contribute:
1. Fork the repository.
2. Create a feature branch.
3. Commit your changes.
4. Open a Pull Request.
Please ensure your code matches the project style and includes relevant tests if applicable.
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
This package is developed and maintained by [JP.Coffee](https://github.com/jp-coffee). Feel free to reach out or open an issue for any questions or suggestions!