rhf-custom-hooks
v1.0.1
Published
Custom React Hook Form hooks for dynamic forms
Readme
rhf-custom-hooks
A collection of advanced, strictly-typed custom hooks for React Hook Form to handle complex, dynamic form logic including dependent field options, visibility/interaction states, and value resets.
These hooks are designed to keep your components clean by allowing you to extract form logic and rules into separate, testable files.
Installation
npm install rhf-custom-hooks react react-hook-form
# or
yarn add rhf-custom-hooks react react-hook-form
# or
pnpm add rhf-custom-hooks react react-hook-formBest Practices: Code Structure
To maintain a clean and scalable codebase, it is highly recommended to extract your form rules (options, interactions, resets, value changes) into separate files, away from your React components. This promotes reusability, easier testing, and separation of concerns.
Example Directory Structure
src/
features/
user/
components/
UserForm.tsx
rules/
userFormRules.tsDefining Rules (userFormRules.ts)
import { InteractionRules, OptionsRules, ValueChangeRules, ResetRules } from 'rhf-custom-hooks';
import { UserFormValues } from '../types';
export const interactionRules: InteractionRules<UserFormValues> = {
discountCode: {
isVisible: (formValues) => formValues.hasDiscount === true,
isDisabled: (formValues, externalState) => externalState?.isLoading === true,
},
};
export const optionsRules: OptionsRules<UserFormValues> = {
city: {
watch: ['country'],
getOptions: (watchedValues) => {
if (watchedValues.country === 'US') return ['New York', 'Los Angeles'];
if (watchedValues.country === 'UK') return ['London', 'Manchester'];
return [];
},
},
};
export const valueChangeRules: ValueChangeRules<UserFormValues> = {
totalPrice: {
watch: ['quantity', 'price'],
setValue: (watchedValues) => {
return (watchedValues.quantity || 0) * (watchedValues.price || 0);
},
},
};
export const resetRules: ResetRules<UserFormValues> = {
city: {
watch: ['country'],
resetValue: '', // Reset city to empty string when country changes
},
};Using Rules in a Component (UserForm.tsx)
import React from 'react';
import { useForm } from 'react-hook-form';
import {
useFormInteraction,
useFormFieldOptions,
useFormValueChange,
useFormReset,
FormVisibilityProvider
} from 'rhf-custom-hooks';
import {
interactionRules,
optionsRules,
valueChangeRules,
resetRules
} from '../rules/userFormRules';
import { UserFormValues } from '../types';
export const UserForm = () => {
const { control, setValue, resetField } = useForm<UserFormValues>();
const [isLoading, setIsLoading] = React.useState(false);
// 1. Interaction (Visibility & Disabled states)
const interaction = useFormInteraction({
control,
rules: interactionRules,
externalState: { isLoading },
});
// 2. Options (Dynamic Dropdowns)
const options = useFormFieldOptions({
control,
rules: optionsRules,
});
// 3. Value Changes (Calculated fields)
useFormValueChange({
control,
setValue,
rules: valueChangeRules,
});
// 4. Resets (Clear dependent fields)
useFormReset({
control,
resetField,
rules: resetRules,
});
return (
<form>
{/* ... other fields */}
<FormVisibilityProvider show={interaction.discountCode.isVisible}>
<input
name="discountCode"
disabled={interaction.discountCode.isDisabled}
placeholder="Discount Code"
/>
</FormVisibilityProvider>
</form>
);
};Detailed Hooks Documentation & Use Cases
useFirstRender
Utility hook to check if the component is being rendered for the first time. Useful for skipping side-effects or initialization logic on mount.
Use Case: Preventing an API call from running immediately on component mount when using a useEffect that depends on a state that might change later.
import { useEffect } from 'react';
import { useFirstRender } from 'rhf-custom-hooks';
const MyComponent = ({ someProp }) => {
const isFirstRender = useFirstRender();
useEffect(() => {
if (isFirstRender) return; // Skip the first render
// This will only run on subsequent renders when someProp changes
console.log('someProp changed:', someProp);
}, [someProp, isFirstRender]);
return <div />;
};useFormFieldOptions
Dynamically generate options for a field based on the values of other watched fields or external state.
Use Case: Cascading dropdowns. For example, a "State/Province" dropdown should only display states relevant to the selected "Country". When the "Country" changes, the options for "State" immediately update.
import { useForm } from 'react-hook-form';
import { useFormFieldOptions } from 'rhf-custom-hooks';
const { control } = useForm();
const options = useFormFieldOptions({
control,
rules: {
state: {
watch: ['country'], // Re-evaluates getOptions when 'country' changes
getOptions: (watchedValues, externalState) => {
if (watchedValues.country === 'USA') {
return [{ label: 'California', value: 'CA' }, { label: 'Texas', value: 'TX' }];
}
return [];
}
}
}
});
// Render the select
return (
<select>
{options.state?.map(opt => (
<option key={opt.value} value={opt.value}>{opt.label}</option>
))}
</select>
);useFormInteraction & FormVisibilityProvider
Manage form field interaction states like visibility and disabled state. Allows you to declare complex conditions for when a field should be visible or disabled.
Use Case:
- Visibility: Hiding a "Spouse Name" field unless "Marital Status" is set to "Married".
- Disabled: Disabling the submit button or form inputs while data is being submitted to the server (using
externalState).
import { useForm } from 'react-hook-form';
import { useFormInteraction, FormVisibilityProvider } from 'rhf-custom-hooks';
const { control } = useForm();
const interaction = useFormInteraction({
control,
rules: {
spouseName: {
isVisible: (formValues) => formValues.maritalStatus === 'Married',
isDisabled: (formValues, externalState) => externalState.isSubmitting
}
},
externalState: { isSubmitting: false }
});
// FormVisibilityProvider handles conditional rendering. If `show` is false, it renders nothing.
return (
<FormVisibilityProvider show={interaction.spouseName.isVisible}>
<input
name="spouseName"
disabled={interaction.spouseName.isDisabled}
/>
</FormVisibilityProvider>
);useFormReset
Automatically reset fields to a default value when their dependencies (watched fields) change. It also handles manual overrides gracefully if a user manually sets a value.
Use Case: If a user selects "USA" as their country, and "California" as their state, but then changes their country to "Canada", the "State" field should be automatically cleared out because "California" is no longer valid.
import { useForm } from 'react-hook-form';
import { useFormReset } from 'rhf-custom-hooks';
const { control, resetField } = useForm();
const { resetOverrides, forceReset } = useFormReset({
control,
resetField,
rules: {
state: {
watch: ['country'],
resetValue: null // Clears the 'state' field when 'country' changes
}
}
});
// You can use resetOverrides to temporarily prevent auto-resetting
// Or forceReset() to manually trigger a reset evaluationuseFormValueChange
Automatically calculate and update a field's value when dependent fields change, featuring deep equality checks to prevent unnecessary re-renders or infinite loops.
Use Case: An invoice form where the "Total Price" field needs to automatically reflect quantity * unitPrice. If either quantity or unitPrice changes, the total price is recalculated and set in the form.
import { useForm } from 'react-hook-form';
import { useFormValueChange } from 'rhf-custom-hooks';
const { control, setValue } = useForm();
useFormValueChange({
control,
setValue,
rules: {
totalPrice: {
watch: ['quantity', 'unitPrice'],
setValue: (watchedValues) => {
const qty = watchedValues.quantity || 0;
const price = watchedValues.unitPrice || 0;
return qty * price;
}
}
}
});License
MIT
