form-hook-kit
v1.2.4
Published
A type-safe form management library for React and React Native with hooks-based API, Yup validation, and 100% test coverage
Downloads
66
Maintainers
Readme
form-hook-kit
A lightweight, flexible form management library for React and React Native with a hooks-based API and Yup validation.
Author: bc-bane
License: MIT
Platform tested: React 18+ & React Native
Features
- Type-safe - Full TypeScript support with 100% type coverage
- Cross-platform - Works with React and React Native
- React Native Compatible - No native iOS/Android code - works with legacy architecture, new architecture, and Android 16KB page size
- Validation - Powered by Yup for robust schema validation
- Hooks-based - Modern React hooks API
- Context-based - Efficient state management with React Context
- Performant - Memoized functions, optional debounced validation, minimal re-renders
- Developer Tools - Built-in DevTools component for debugging (development only)
- Flexible - Works with any UI component library
- Well-tested - 100% test coverage
- Production-ready - Comprehensive documentation and examples
Why form-hook-kit?
Comparison with Other Form Libraries
vs. Formik
Key Differences:
- API Style - form-hook-kit is hooks-only, Formik supports both hooks and render props
- React Native - Both support React Native with different approaches
- Yup Integration - Both have built-in Yup support
- Community - Formik has larger community and more plugins
When to use Formik instead:
- You need a battle-tested library with years of production use
- You want access to a larger ecosystem of community plugins
- Your project already uses Formik
vs. React Hook Form
Key Differences:
- State Management - form-hook-kit uses Context, React Hook Form uses refs
- Input Style - form-hook-kit uses controlled inputs, React Hook Form uses uncontrolled
- Yup Integration - form-hook-kit has built-in support, React Hook Form requires resolver
- Performance - React Hook Form may be faster for very large forms
- Popularity - React Hook Form has larger user base
When to use React Hook Form instead:
- You need uncontrolled inputs for maximum performance
- You prefer ref-based form tracking
- You have very large forms (100+ fields)
vs. Final Form
Key Differences:
- API Style - form-hook-kit is hooks-only, Final Form uses subscriptions
- TypeScript - form-hook-kit is TypeScript-first, Final Form has TypeScript support
- React Version - form-hook-kit requires React 16.8+, Final Form supports older versions
- Maturity - Final Form is more established
When to use Final Form instead:
- You need field-level subscriptions for complex performance optimization
- You're migrating from Redux Form
- You need to support older React versions
vs. Custom Solutions
Advantages over rolling your own:
- Well-tested - 100% test coverage with comprehensive test suite
- Edge cases handled - Validation, error handling, field refs all included
- TypeScript support - Full type safety out of the box
- Ready to use - No need to build and maintain form infrastructure
- Documentation - Complete docs and examples
Feature Comparison Table
| Feature | form-hook-kit | Formik | React Hook Form | Final Form | |---------|-------------------|--------|-----------------|------------| | React Native Support | ✓ Native | ✓ Supported | ✓ Supported | ✓ Supported | | TypeScript | ✓ First-class | ✓ Supported | ✓ First-class | ✓ Supported | | Yup Integration | ✓ Built-in | ✓ Built-in | Via resolver | Via plugin | | API Style | Context + Hooks | Context + Hooks | Refs + Hooks | Subscriptions | | Hooks-only API | ✓ Yes | Mixed | ✓ Yes | Mixed | | Built-in Field Refs | ✓ Yes | ✓ Yes | ✓ Yes | ✓ Yes | | Learning Curve | Low | Low-Medium | Medium | Medium-High |
When to Choose form-hook-kit
Choose form-hook-kit if you:
- Are building a React or React Native app
- Need React Native new architecture compatibility (no native code dependencies)
- Want a simple, hooks-based API
- Prefer context-based state management
- Need TypeScript support with 100% type coverage
- Use Yup for validation
- Want built-in Yup integration without extra packages
- Prefer controlled inputs over uncontrolled
- Need compatibility with Android 16KB page size
Installation
npm install form-hook-kit yup
# or
yarn add form-hook-kit yup
# or
pnpm add form-hook-kit yupQuick Start
import React from 'react';
import * as yup from 'yup';
import {FormProvider, useForm, useFormField} from 'form-hook-kit';
const schema = yup.object({
email: yup.string().email('Invalid email').required('Email is required'),
password: yup.string().min(8).required('Password is required'),
});
function EmailField() {
const {value, error, onChange, onBlur} = useFormField('email');
return (
<div>
<input
type="email"
value={value || ''}
onChange={onChange}
onBlur={onBlur}
placeholder="Email"
/>
{error && <span className="error">{error}</span>}
</div>
);
}
function LoginForm() {
const {validateForm, values} = useForm();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const errors = validateForm();
if (Object.values(errors).every(error => !error)) {
console.log('Form submitted:', values);
}
};
return (
<form onSubmit={handleSubmit}>
<EmailField />
<button type="submit">Login</button>
</form>
);
}
export default function App() {
return (
<FormProvider schema={schema} initialValues={{email: '', password: ''}}>
<LoginForm />
</FormProvider>
);
}📚 For complete examples including React Native, see USAGE.md
Comprehensive Demo Applications
We provide two extensive, production-ready demo applications that showcase all form-hook-kit features:
React Web Registration Demo (examples/react-registration-demo/)
A full-featured React web application demonstrating:
- Complete Registration Form - Multiple field types (text, email, password, number, URL, textarea, checkbox)
- Yup Schema Validation - Custom error messages, required fields, format validation, length constraints
- Individual Field Components - Isolated re-renders using
useFormFieldhook - Performance Monitoring - Real-time metrics with
useFormPerformancehook - DevTools Integration - Visual UI panel for debugging form state
- Configurable Validation Debouncing - Adjustable delay slider (0-1000ms)
- Modern Stack - Vite, React 19, TypeScript, full type safety
Run the demo:
cd examples/react-registration-demo
npm install
npm run devReact Native Registration Demo (examples/react-native-registration-demo.tsx)
A comprehensive React Native application demonstrating:
- Complete Registration Form - Multiple field types (text, email, password, phone, number, textarea, checkbox)
- Yup Schema Validation - Custom error messages, cross-field validation (password confirmation), format validation
- Individual Field Components - Isolated re-renders using
useFormFieldhook - Performance Monitoring - Real-time metrics with
useFormPerformanceanduseValidationPerformancehooks - DevTools Integration - Console mode for React Native debugging
- React Native-Specific Features:
KeyboardAvoidingViewfor keyboard handlingSafeAreaViewfor safe area insets- Platform-specific styling (iOS/Android)
- Phone number formatting with custom formatter
- Password visibility toggle
- Focus management with field refs
- Advanced Features:
- Manual validation examples
- Multiple values update (reset form, fill sample data)
- Form values and errors display
- Configurable validation debouncing (300ms default)
Use the demo:
- Copy
examples/react-native-registration-demo.tsxto your React Native app'sApp.tsx - Install dependencies:
npm install form-hook-kit yup - Run:
npx react-native run-iosornpx react-native run-android
Both demos serve as excellent references for learning form-hook-kit capabilities and as production-ready starting points for your own forms.
API Reference
For complete API documentation, advanced usage, React Native examples, and performance optimization, see USAGE.md.
FormProvider
The main component that wraps your form and provides context.
Props:
schema(required): Yup validation schemainitialValues(optional): Initial form values (default:{})initialErrors(optional): Initial error state (default:{})validationDebounce(optional): Debounce validation in milliseconds for performance optimization (default:0)children(required): Form components
<FormProvider
schema={yupSchema}
initialValues={{email: '', password: ''}}
initialErrors={{}}
validationDebounce={300} // Optional: debounce validation for better performance
>
{children}
</FormProvider>useForm()
Hook to access the form context. Must be used within a FormProvider.
Returns:
values: Object containing all form valueserrors: Object containing all form errorsfieldRefs: Ref object for managing field focuschangeValue(params): Function to update a single fieldchangeValues(values): Function to update multiple fieldsclearError(name): Function to clear error for a fieldsetError(params): Function to set error for a fieldvalidateField(name, value?): Function to validate a single fieldvalidateForm(): Function to validate entire form
const {
values,
errors,
changeValue,
validateForm,
fieldRefs,
} = useForm();useFormField(name)
Convenient hook for managing a single form field. Provides pre-configured handlers.
Parameters:
name(string): The field name
Returns:
value: Current field valueerror: Current field errorname: Field nameonChange: Handler for React web inputs (e.target.value)onChangeValue: Handler for React Native or custom value changesonBlur: Handler for field blur (triggers validation)onFocus: Handler for field focus (clears errors)setRef: Function to set field ref for focus management
const {value, error, onChange, onBlur} = useFormField('email');useFormPerformance()
NEW in v1.2.0 - Hook to monitor form performance metrics. Useful for debugging and optimization.
Returns:
renderCount: Number of times the component has renderedlastRenderTime: Time taken for the last render (ms)validationCount: Number of validations performedaverageValidationTime: Average validation time (ms)fieldChangeCount: Number of field changes
import {useFormPerformance} from 'form-hook-kit';
function MyForm() {
const metrics = useFormPerformance();
console.log('Renders:', metrics.renderCount);
console.log('Avg validation time:', metrics.averageValidationTime);
return <div>...</div>;
}useValidationPerformance()
NEW in v1.2.0 - Hook to track validation performance with timing metrics.
import {useValidationPerformance} from 'form-hook-kit';
function MyForm() {
const {validateField, validateForm, metrics} = useValidationPerformance();
const handleSubmit = () => {
validateForm();
console.log('Validation took:', metrics.lastValidationTime, 'ms');
};
return <button onClick={handleSubmit}>Submit</button>;
}FormDevTools
NEW in v1.2.0 - Cross-platform development tool for inspecting form state and performance.
Platform Support:
- Web: Visual UI panel (default)
- React Native: Console logging mode (works with React Native Debugger, Flipper, or Metro logs)
Import from separate entry point:
import {FormDevTools} from 'form-hook-kit/devtools';
// Web - shows UI panel
function WebForm() {
return (
<FormProvider schema={schema}>
<MyFormFields />
{process.env.NODE_ENV === 'development' && <FormDevTools />}
</FormProvider>
);
}
// React Native - logs to console
function MobileForm() {
return (
<FormProvider schema={schema}>
<MyFormFields />
{__DEV__ && <FormDevTools mode="console" autoLog />}
</FormProvider>
);
}Props:
mode?: 'ui' | 'console' | 'none'- Display mode (auto-detects platform by default)autoLog?: boolean- Auto-log changes in console mode (default:false)logPrefix?: string- Custom log prefix (default:'[FormDevTools]')position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'- UI panel position (default:'bottom-right')defaultOpen?: boolean- UI panel open by default (default:true)
Console Mode (React Native):
When using mode="console", you can manually inspect form state:
// In React Native Debugger or browser console:
global.formDevTools.logValues() // Log current values
global.formDevTools.logErrors() // Log current errors
global.formDevTools.logMetrics() // Log performance metrics
global.formDevTools.logAll() // Log everythingProps:
position(optional):'top-left'|'top-right'|'bottom-left'|'bottom-right'(default:'bottom-right')defaultOpen(optional): Whether to show by default (default:false)
Documentation
- USAGE.md - Complete usage guide with examples
- CHANGELOG.md - Version history
Contributing
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature/your-feature) - Make your changes and add tests
- Ensure tests pass (
npm test) - Commit your changes (
git commit -m 'Add some feature') - Push to the branch (
git push origin feature/your-feature) - Open a Pull Request
Please ensure:
- All tests pass
- Code follows the existing style
- New features include tests
- TypeScript types are properly defined
Security
When using form-hook-kit:
- Always validate user input with proper Yup schemas
- Keep your dependencies up to date
- Sanitize any user input before displaying it
- Follow React security best practices
To report security vulnerabilities, please open an issue on GitHub.
License
MIT License - see LICENSE file for details
Credits
Author: bc-bane
Built for production use in React and React Native applications.
Designed to be simple, performant, and flexible.
