# useForm Hook

A custom React hook that provides direct access to form context values and controls within the Form component.

## Overview

The `useForm` hook allows components to directly interact with the form's state management system without going through the `FormField` wrapper. This is useful for creating custom form controls, debugging tools, or implementing complex form logic.

## Installation

```tsx
import { useForm } from '@delightui/components';
```

## API

### `useForm<T>()`

Returns the complete form context with all state and control functions.

#### Return Value

```typescript
{
  formRef: RefObject<HTMLFormElement>;
  formState: T;
  formErrors: FormErrors<T>;
  updateFieldValue: (name: string, value: FieldValue) => void;
  updateFieldError: (name: keyof T, error: string) => void;
  updateFieldValidators: (name: keyof T, validate?: FieldValidationFunction) => void;
  updateRequiredFields: (name: keyof T, required?: boolean) => void;
  onFormSubmit: FormEventHandler<HTMLFormElement>;
  resetForm: () => void;
}
```

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `formRef` | `RefObject<HTMLFormElement>` | Reference to the form element |
| `formState` | `T` | Current values of all form fields |
| `formErrors` | `FormErrors<T>` | Current validation errors for each field |
| `updateFieldValue` | `Function` | Updates a specific field's value |
| `updateFieldError` | `Function` | Sets an error message for a field |
| `updateFieldValidators` | `Function` | Registers validation function for a field |
| `updateRequiredFields` | `Function` | Marks a field as required/optional |
| `onFormSubmit` | `Function` | Form submission handler |
| `resetForm` | `Function` | Resets form to initial state |

## Usage Examples

### Basic Usage

```tsx
import { useForm, Form } from '@delightui/components';

const MyCustomField = () => {
  const { formState, updateFieldValue } = useForm();
  
  return (
    <input
      value={formState.myField || ''}
      onChange={(e) => updateFieldValue('myField', e.target.value)}
    />
  );
};

// Usage within Form
<Form formState={{ myField: '' }}>
  <MyCustomField />
</Form>
```

### Type-Safe Usage

```tsx
interface MyFormData {
  username: string;
  email: string;
  age: number;
}

const MyComponent = () => {
  const { formState, formErrors, updateFieldValue } = useForm<MyFormData>();
  
  return (
    <div>
      <input
        value={formState.username || ''}
        onChange={(e) => updateFieldValue('username', e.target.value)}
      />
      {formErrors.username && <span>{formErrors.username}</span>}
    </div>
  );
};
```

### Custom Validation

```tsx
const CustomValidatedField = () => {
  const { updateFieldValidators, updateFieldValue } = useForm();
  
  useEffect(() => {
    // Register custom validation
    updateFieldValidators('customField', (setError, value) => {
      if (value && value.length < 5) {
        setError('Must be at least 5 characters');
        return false;
      }
      return true;
    });
    
    // Cleanup on unmount
    return () => updateFieldValidators('customField', undefined);
  }, [updateFieldValidators]);
  
  return (
    <input onChange={(e) => updateFieldValue('customField', e.target.value)} />
  );
};
```

### Form Debugging Component

```tsx
const FormDebugger = () => {
  const { formState, formErrors, resetForm } = useForm();
  
  return (
    <div style={{ padding: '1rem', background: '#f0f0f0' }}>
      <h4>Form State:</h4>
      <pre>{JSON.stringify(formState, null, 2)}</pre>
      
      <h4>Form Errors:</h4>
      <pre>{JSON.stringify(formErrors, null, 2)}</pre>
      
      <button onClick={resetForm}>Reset Form</button>
    </div>
  );
};
```

### Dynamic Field Management

```tsx
const DynamicFieldManager = () => {
  const { formState, updateFieldValue, updateRequiredFields } = useForm();
  const [fields, setFields] = useState<string[]>([]);
  
  const addField = () => {
    const fieldName = `field_${fields.length}`;
    setFields([...fields, fieldName]);
    updateFieldValue(fieldName, '');
    updateRequiredFields(fieldName, true);
  };
  
  return (
    <div>
      {fields.map(field => (
        <input
          key={field}
          value={formState[field] || ''}
          onChange={(e) => updateFieldValue(field, e.target.value)}
        />
      ))}
      <button onClick={addField}>Add Field</button>
    </div>
  );
};
```

## When to Use

Use `useForm` when you need:

- **Custom form controls** that require direct access to form state
- **Complex validation logic** that spans multiple fields
- **Dynamic field management** with programmatic control
- **Form debugging tools** or state visualization
- **Integration with third-party components** that don't work with FormField

## Best Practices

1. **Always use within Form**: The hook must be used inside a Form component
2. **Clean up validators**: Remove validators when components unmount
3. **Type your form data**: Use generics for type-safe form state
4. **Prefer FormField for standard inputs**: Use FormField when possible for automatic integration
5. **Handle errors gracefully**: Check for context availability in reusable components

## Comparison with FormField

| Feature | FormField | useForm |
|---------|-----------|---------|
| Automatic validation | ✅ | ❌ (manual) |
| Error display | ✅ | ❌ (manual) |
| Required field handling | ✅ | ❌ (manual) |
| Direct state access | ❌ | ✅ |
| Custom logic flexibility | Limited | Full |
| Setup complexity | Low | Medium |

## Error Handling

The hook will throw an error if used outside a Form component:

```tsx
// ❌ This will throw an error
const MyComponent = () => {
  const form = useForm(); // Error: useForm must be used within a Form component
  return <div>...</div>;
};

// ✅ Correct usage
const MyComponent = () => {
  return (
    <Form>
      <MyFormContent />
    </Form>
  );
};

const MyFormContent = () => {
  const form = useForm(); // Works!
  return <div>...</div>;
};
```

## TypeScript Support

The hook is fully typed and supports generic type parameters:

```tsx
// Basic usage (untyped)
const form = useForm();

// Typed usage
const form = useForm<MyFormData>();

// Alternative typed version
const form = useFormTyped<MyFormData>();
```

## Related

- [Form Component](../components/organisms/Form.md)
- [FormField Component](../components/molecules/FormField.md)
- [Form Validation Guide](../guides/form-validation.md)