๐Ÿ“‹ React Hooks for forms validation (Web + React Native)

Overview

Performant, flexible and extensible forms with easy to use validation.

npm downloads npm npm Discord

English | ็นไธญ | ็ฎ€ไธญ | ๆ—ฅๆœฌ่ชž | ํ•œ๊ตญ์–ด | Franรงais | Italiano | Portuguรชs | Espaรฑol | ะ ัƒััะบะธะน | Deutsch | Tรผrkรงe

Features

Install

npm install react-hook-form

Links

Quickstart

import React from 'react';
import { useForm } from 'react-hook-form';

function App() {
  const { register, handleSubmit, errors } = useForm(); // initialize the hook
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} /> {/* register an input */}
      <input name="lastname" ref={register({ required: true })} />
      {errors.lastname && 'Last name is required.'}
      <input name="age" ref={register({ pattern: /\d+/ })} />
      {errors.age && 'Please enter number for age.'}
      <input type="submit" />
    </form>
  );
}

Sponsors

Thanks go to these kind and lovely sponsors (company and individuals)!

@sayav @lemcii @washingtonsoares @lixunn @SamSamskies @peaonunes @wilhelmeek @iwarner @joejknowles @chris-gunawardena @Tymek @Luchanso @vcarel @gragland @tjshipe @krnlde @msutkowski @mlukaszczyk

Backers

Thanks go to all our backers! [Become a backer].

Organizations

Thanks go to these wonderful organizations! [Contribute].

Contributors

Thanks go to these wonderful people! [Become a contributor].

Comments
  • #1580 Controller with render props API

    #1580 Controller with render props API

    ๐Ÿ”Origin

    This PR is led by a TS bug #1580 where required props will require to fulfill again at the props.

    Example CSB: https://codesandbox.io/s/react-hook-form-controller-template-qrtco

    type MyInputProps = {
      value: any;
      onChange: () => void;
    };
    
    function MyInput(props: MyInputProps) {
      return <input name="FirstName" {...props} />;
    }
    
    <Controller
      as={<input name="FirstName" />} // result in TS error for required onChange and value 
      defaultValue="FirstName"
      control={control}
    />
    

    โœ๏ธSolutions

    Render prop was purposed by @kotarella1110 which also lead to a discussion around shaping better API. Here are the options


    OPTION A only support Render Props for Controller

    cons:

    1. verbose for simple usage
    2. impact API consistency between ErrorMessage and Controller

    pros:

    1. consistent usage with Controller
    2. less code inside lib
    3. predictable result

    OPTION B support both as and render

    cons:

    1. less intuitive consider providing two options: as vs render. this could lead to confusion.
    2. lack of consistent usage

    pros:

    1. consistent API across ErrorMessage & Controller
    2. more code inside lib
    3. simple usage option, plug-in & play
    4. the community seems to be keener with both options

    โŒ OPTION C render support render props and component

    This approach having issues with good/easy TS support and having issue useFieldArray (which lead input to remount)

    Screen Recording 2020-05-30 at 10 46 28 am


    ๐Ÿ“งPoll result

    The above options lead us into discussion and poll on twitter. Below is a good result.

    image


    ๐Ÿ“ฆWhat's next?

    The plan is to release an RC.2 version with option B and waiting for the community's feedback for 2 weeks before releasing the new V6. During the period, if users raise concerns over the new API and we will re-look at option A again.


    ๐Ÿ“˜Changes

    • [x] Controller

    Less of a breaking change for existing users, simple usage remain while still give the user the full control with render prop. Remove the following props

    • onChange
    • onChangeName
    • onBlur
    • onBlurName
    • valueName

    Simple usage as below, will not be impacted:

    <Controller as={TextField} control={control} name="test" />
    

    Usage involed configration and those remmoved props:

    -<Controller 
    -  as={CustomInput} 
    -  valueName="textValue"
    -  onChangeName="onTextChange"
    -  control={control} 
    -  name="test"  
    -/>
    +<Controller 
    +  render={({ onChange, onBlur, value }) => (
    +     <CustomInput onTextChange={onChange} onBlur={onBlur} textValue={value} />
    +  )}
    +  control={control} 
    +  name="test"  
    +/>
    

    • [x] ErrorMessage

    change render props from children to render, usage change from the ability to use both to either. you can either use as or render. for multiple error messages, you will have to use render

    <ErrrorMessage errors={errors} as="p" />
    <ErrrorMessage errors={errors} render={({message}) => {message}} />
    

    Note: Both ErrorMessage and Controller contains as and render props. Users should either use as or render.

    โŒ<Controller as={TextField}  render={(props) => <TextField {...props} />}/>
    โŒ<ErrorMessage as={TextField}  render={({ message }) => {message} }/>
    
    โœ…<Controller as={TextField}  />
    โœ…<Controller render={(props) => <TextField {...props} />}/>
    
    โœ…<ErrorMessage as={TextField} />
    โœ…<ErrorMessage render={({ message }) => {message} }/>
    
    opened by bluebill1049 111
  • [Bug]: Regression: TS2589: Type instantiation is excessively deep and possibly infinite

    [Bug]: Regression: TS2589: Type instantiation is excessively deep and possibly infinite

    Version Number

    7.16.2

    Codesandbox/Expo snack

    Codesandbox still doesn't allow me to install the latest version

    Steps to reproduce

    1. Upgrade from 7.16.1 to 7.16.2, no other changes
    2. Cue error

    Expected behaviour

    TypeScript compilation should succeed without any warnings. I believe #6658 is the cause of introducing this error, this is a regression of #4441

    What browsers are you seeing the problem on?

    No response

    Relevant log output

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
    TS 
    opened by StampixSMO 64
  • ๐Ÿ’ˆ useFieldArray

    ๐Ÿ’ˆ useFieldArray

    New custom hook for FieldArray:

    โœจ useFieldArray

    https://codesandbox.io/s/react-hook-form-usefieldarray-vy8fv

      const { fields, append, prepend, remove, move, swap, insert } = useFieldArray({
        control, // optional
        name: "test"
      });
    

    latest beta version: 4.5.0-beta.2

    • [x] building the hook
    • [x] unit test
    • [x] automation
      • normal flow
      • with default values
    • [x] website documenation
    opened by bluebill1049 64
  • isValid is sometimes false despite no errors

    isValid is sometimes false despite no errors

    Describe the bug I sometimes get isValid = false despite having no visible errors and errors object being an empty object ({})

    To Reproduce I do not yet have a reproducable sandbox, but I already found a code piece that might be the problem. Please see additional context

    Expected behavior isValid should always reflect what the errors object contains (e.g. isValid = Object.keys(errors).length === 0)

    Desktop (please complete the following information):

    • OS: Windows 10 202001
    • Browser: Microsoft Edge
    • Version: 86.0.621.0 (Official build) canary (64-bit)

    Additional context The problematic line could be this code piece here: https://github.com/react-hook-form/react-hook-form/blob/03216edb0b29bae631fb752e6ec612111d82798d/src/useForm.ts#L341 which triggers revalidation but without providing an isValid parameter as the 4th parameter. Hence this line https://github.com/react-hook-form/react-hook-form/blob/03216edb0b29bae631fb752e6ec612111d82798d/src/useForm.ts#L218 will resolve in !!isValid which essentially means !!undefined === false.

    AFAIK the problem only appears on async filled inputs (inputs that get their value via an api request).

    opened by krnlde 58
  • RFC: async defaultValues

    RFC: async defaultValues

    Summary

    The current status of setting defaultValues from async data source is using reset:

    useEffect(() => {
      reset({
         firstName: 'test',
      })
    });
    

    honestly, this is probably not a pretty and clean approach... a few weeks before we had a feature request regarding async defaultValues: https://github.com/react-hook-form/react-hook-form/issues/2335

    Proposal Solutions

    1. defaultValues accept Promise, and promise will get resolve after useEffect, although I do have concern over the confusion which prop support both object and Promise.
    const { formState: { isLoading } } = useForm({
      defaultValues: async () => ({ firstName: 'test' })
      // defaultValues: new Promise()
    }, [])
    

    happy to discuss more options on the table too.

    feature request 
    opened by bluebill1049 58
  • Remove Dirty Prop

    Remove Dirty Prop

    I would like to be able to disable the dirty prop as it is causing unnecessary re renders of components, this is happening when the dirty prop is toggling, I would like to be able to override this by passing a prop of dirtyDisable to useForm which will make the dirty prop either always true or just remove it from the useForm return all together.

    wont be worked on 
    opened by The-Code-Monkey 57
  • Custom yup validation with useFieldArray doesn't always trigger re-render

    Custom yup validation with useFieldArray doesn't always trigger re-render

    Describe the bug I have custom yup validation which checks if there are same names in field array and returns false if there are 2 or more items with the same name. This works fine if you add 2 items to field array. When you add third one, validation is always "1 step behind" after rendering. It is validated, but render is not triggered so the error css is not displayed for the last field that is invalid.

    To Reproduce Steps to reproduce the behavior:

    1. Go to sandbox link
    2. Click on "+ Custom job" button at the top of the page, new job is added
    3. Click on "+ Custom job" button at the top of the page, new job is added and validation occurred, both new jobs with empty names are marked with red border to indicate error
    4. Click on "+ Custom job" button at the top of the page, third new job is added, but validation didn't trigger re-render and last invalid custom job doesn't have red border. This pattern happens each time with any dynamically added custom job, but only for third added item. If you add more, always the last one is not marked as invalid. There is also log in the console when validation occurs and when rendering occurs.

    Codesandbox link https://codesandbox.io/s/react-hook-form-usefieldarray-owyo0?file=/src/index.js

    Expected behavior All new custom jobs with empty names should be marked red, re-render should be triggered after each validation.

    question 
    opened by rvision 56
  • Field arrays lose their focus or position when reset

    Field arrays lose their focus or position when reset

    Describe the bug As part of our auto-save mechanism, we reset the form before save so that the default values will be set properly for the next auto save.

    The auto save, and therefore the reset, happen on a timer, which means that the user may have a field focused when the save happens.

    If the field they have focused is in a field array, then the documented method of using the field id as key causes the entire array item field to rerender because the id is recreated upon reset.

    We're using stable keys to work around this, but that may be a bug.

    Even with this, if the user has a text input focused when a reset happens and their cursor is somewhere other than the beginning of the field, the cursor will jump to the beginning of the text input. This is not the case for normal inputs, only for field arrays.

    The reason appears to be that field arrays actually modify the value attribute of the element, which is different than regular fields. I can reproduce this by modifying value on a timer without involving react hook form.

    To Reproduce Steps to reproduce the behavior:

    1. Go to https://codesandbox.io/s/react-hook-form-usefieldarray-template-forked-ht83m?file=/src/index.js
    2. Click on the first name field and replace the text with "Test"
    3. Click "RESET DELAY" and then quickly click on the first name field, positioning your cursor at the end of the word "Test"
    4. Wait for the timeout and observe that the cursor jumps to the beginning of the field

    Codesandbox link (Required) https://codesandbox.io/s/react-hook-form-usefieldarray-template-forked-ht83m?file=/src/index.js

    Expected behavior I'd expect the value attribute to not change so that the cursor does not jump. I'd also expect that the field id does not change on reset so it could be used as a stable key, or for the documentation to be updated accordingly.

    Thanks!

    enhancement 
    opened by aaronjensen 52
  • useWatch within a nested useFieldArray removing a item just before another causes useWatch go out of sync

    useWatch within a nested useFieldArray removing a item just before another causes useWatch go out of sync

    Describe the bug When using useWatch within a nested useFieldArray removing a item just before another causes useWatch go out of sync. For the item its assigned to it does not pick up the changes, however it seems to take those of the next added item.

    To Reproduce

    1. Create a form with a nested useFieldArray
    2. Append 2 elements to list
    3. Remove the first and type - noticing that the watched prop is not changing
    4. Add a element and something in the second item - noticing that both the first and second items watch component seem to be updating

    Codesandbox link (Required) https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-t29u3?file=/src/nestedFieldArray.js

    Expected behavior useWatch returns the value of the index/item its assigned too

    Desktop (please complete the following information):

    OS: Mac (Mojave 10.14.6) Browser: Chrome Version: 84

    enhancement 
    opened by meman 50
  • IE11 support ?

    IE11 support ?

    Hi,

    Thanks for the great library. I've been using it for all my projects, but it does not work on IE11. Can you add support for this one ?

    I got Syntax error in useForm/index.es.js (line 9)

    If you have IE11, you can try it here https://comptaplan-dev.netlify.com

    Thank you

    question 
    opened by opeah 50
  • Material UI + multiple checkboxes + default selected

    Material UI + multiple checkboxes + default selected

    I am trying to build a form which accommodates multiple 'grouped' checkboxes using Material UI.

    The checkboxes are created async from a HTTP Request.

    I want to provide an array of the objects IDs as the default values:

    defaultValues: { boat_ids: trip?.boats.map(boat => boat.id.toString()) || [] },

    Also, when I select or deselect a checkbox, I want to add/remove the ID of the object to the values of react-hook-form.

    How can I achieve that?

    Here is a sample that I am trying to reproduce the issue:

    https://codesandbox.io/s/smoosh-dream-zmszs?file=/src/App.js

    Right now with what I have tried, I get this:

    Screenshot 2020-04-28 at 03 10 04

    Bonus point, validation of minimum selected checkboxes using Yup

    boat_ids: Yup.array() .min(2, ""),

    Thanks in advance!

    question 
    opened by mKontakis 48
  • issue: additionalProperties error not returned

    issue: additionalProperties error not returned

    Version Number

    7.41.3

    Codesandbox/Expo snack

    https://codesandbox.io/s/goofy-snowflake-684x1g?file=/src/App.tsx

    Steps to reproduce

    1. Create a form, creating a schema where additionalProperties = false
    2. Reset it using a property unknown to the schema
    3. isValid = false, but errors = {}

    Overriding the resolver function, I think that it is happening because the error has an empty key:

    image

    Expected behaviour

    1. Create a form, creating a schema where additionalProperties = false
    2. Reset it using a property unknown to the schema
    3. isValid = false, but errors should includes a message like must NOT have additional properties

    What browsers are you seeing the problem on?

    Firefox, Chrome

    Relevant log output

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
    opened by teobmg 0
  • issue: Focus is not working after reset

    issue: Focus is not working after reset

    Version Number

    7.41.3

    Codesandbox/Expo snack

    https://codesandbox.io/s/rhf-after-reset-focus-problem-0jjb2w

    Steps to reproduce

    1.Press submit while input is empty and see focus and error. 2.You enter input and delete input, apply step 1 and see focus and error. 3.Press reset button then press submit, the focus is not working.

    Expected behaviour

    Hi, I'm using material-ui + RHF+ react-imask at same time for coding custom library. I'm passing RHF field ref to TextField for focusing and it's working good. After then i'm passing to input component third-party react-imask component (it's getting ref), not problem, the focusing is working perfect. But when i used the reset function, i lost the focus behavior.

    screen-recorder-sun-jan-01-2023-14-40-07.webm

    What browsers are you seeing the problem on?

    Firefox, Chrome, Edge

    Relevant log output

    No response

    Code of Conduct

    • [ ] I agree to follow this project's Code of Conduct
    question 
    opened by atillaaliyev 4
  • issue: IsValid is false but errors is empty

    issue: IsValid is false but errors is empty

    Version Number

    7.41.2

    Codesandbox/Expo snack

    https://codesandbox.io/s/bold-monad-7beuxs?file=/src/App.tsx

    Steps to reproduce

    There are two dates: startDate and endDate. Each date can be moved from 15 minutes up or down thanks to + and - buttons next to it.

    The purpose is to detect endDate going before startDate causing a date overlapping.

    • In order to check that we use a when validator on the endDate that depends on the startDate value.
    • react-hook-form is configured in onChange mode.

    To trigger this rule I can do one of the two possible actions.

    1. Decrement endDate for it to be before startDate.
    2. Increment startDate to be after endDate.

    There is no issue with the first method, but the second has some.

    • If you change endDate (the one with the rule "when" from the yup schema) you can see isValid going to false and the errors object gets updated.
    • But if you change startDate, you can see that isValid goes false but the errors object is not updated.

    Expected behavior

    isValid and errors are sync no matter if i change startDate or endDate and rules related to each other get correctly triggered.

    How can { "isValid": false, "errors": {} } be possible? As the validity is determined by if there are errorsโ€ฆ

    What browsers are you seeing the problem on?

    Firefox, Chrome, Safari, Edge

    Relevant log output

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
    question 
    opened by ScreamZ 7
  • Allow keepIsSubmitSuccessful flag

    Allow keepIsSubmitSuccessful flag

    This ticket by @ikevinws describes the desired behavior.

    Please note:

    • lint will complain about a "@ts-nocheck" in setup.native.ts
    • cypress will fail the setValueAsyncStrictMode.cy.ts test

    Both problems also occur on current master and are unrelated to the given change.

    Would be sweet to see this merged :)

    opened by stefanpl 4
  • โญ๏ธ next (7.42.0)

    โญ๏ธ next (7.42.0)

    ๐Ÿ“ฝ feature: validate function to include formValues (#9079)

    type FormValues = {
      number1: number;
      number2: number;
    };
    
    // Making exported validate function isolated for validation
    export function validateNumber(_: number, formValus: FormValues) {
      return formValus.number1 + formValus.number2 === 3;
    }
    
    export default function App() {
      const { register, handleSubmit } = useForm({
        defaultValues: {
          number1: 0,
          number2: 0
        }
      });
    
      return (
        <form onSubmit={handleSubmit((data) => console.log(data))}>
          <input
            type="number"
            {...register("number1", {
              validate: validateNumber,
              valueAsNumber: true
            })}
          />
          <input
            type="number"
            {...register("number2", {
              validate: validateNumber,
              valueAsNumber: true
            })}
          />
         <button>submit</button>
        </form>
      );
    }
    

    ๐Ÿ›ค๏ธ keep track of traversed types to avoid self-referencing while constructing paths for a type (#9540) ๐Ÿ‹๐Ÿปโ€โ™€๏ธ reduced code with unset by weight reduce of 1% (#9575) ๐Ÿ“” fix warning for setValue test case ๐Ÿชœ Improve handleSubmit function

    opened by bluebill1049 2
  • issue: can't get typescript to accept different schema output using zod

    issue: can't get typescript to accept different schema output using zod

    Version Number

    7.38.0

    Codesandbox/Expo snack

    https://codesandbox.io/s/hidden-cloud-vruf30?file=/src/App.tsx:0-718

    Steps to reproduce

    1. Open the Code Sandbox (https://codesandbox.io/s/hidden-cloud-vruf30?file=/src/App.tsx:0-718);
    2. Look at the error at line 25;

    Expected behaviour

    React Hook Form should automatically infer the output type for the schema sent via the resolver property or allow us to set the input and output schema types when using useForm hook.

    What browsers are you seeing the problem on?

    Chrome

    Relevant log output

    No response

    Code of Conduct

    • [X] I agree to follow this project's Code of Conduct
    enhancement 
    opened by diego3g 5
Releases(v7.42.0-next.0)
  • v7.42.0-next.0(Jan 1, 2023)

    ๐Ÿ“ฝ feature: validate function to include formValues (#9079)

    type FormValues = {
      number1: number;
      number2: number;
    };
    
    // Making exported validate function isolated for validation
    export function validateNumber(_: number, formValus: FormValues) {
      return formValus.number1 + formValus.number2 === 3;
    }
    
    export default function App() {
      const { register, handleSubmit } = useForm({
        defaultValues: {
          number1: 0,
          number2: 0
        }
      });
    
      return (
        <form onSubmit={handleSubmit((data) => console.log(data))}>
          <input
            type="number"
            {...register("number1", {
              validate: validateNumber,
              valueAsNumber: true
            })}
          />
          <input
            type="number"
            {...register("number2", {
              validate: validateNumber,
              valueAsNumber: true
            })}
          />
         <button>submit</button>
        </form>
      );
    }
    

    ๐Ÿ›ค๏ธ keep track of traversed types to avoid self-referencing while constructing paths for a type (#9540) ๐Ÿ‹๐Ÿปโ€โ™€๏ธ reduced code with unset by weight reduce of 1% (#9575) ๐Ÿ“” fix warning for setValue test case ๐Ÿชœ Improve handleSubmit function

    thanks to @SimplyLinn & @Mini-ghost

    Source code(tar.gz)
    Source code(zip)
  • v7.41.3(Dec 30, 2022)

  • v7.41.2(Dec 28, 2022)

  • v7.41.1(Dec 23, 2022)

    ๐Ÿž fix #9659 NaN prevent validation update (#9660) ๐Ÿ•ฏ๏ธ close #9524 useWatch return undefined value (#9653) ๐Ÿ“– adjust contributing document (#9641) ๐Ÿ’†๐Ÿป fix #9621 with the inline default value (#9622) ๐Ÿฉป docs: update contribution guidelines (#9605)

    thanks to @Mini-ghost and @stefanpl

    Source code(tar.gz)
    Source code(zip)
  • v7.41.0(Dec 16, 2022)

    ๐Ÿ‘‰ NEW values props

    The following syntax will react to values prop update/changes.

    • values will be reactive to update/change and reset accordingly
    • provide a reset option to keep dirty/touched values potentially
    const values = await fetch('API')
    
    useForm({
      values, // will reset the form when values updates
      // resetOptions: {
      //   keepDirtyValues: true
      // }
    })
    

    ๐Ÿ‘‰ NEW async defaultValues props

    The following syntax will support async defaultValues, so we will manage the reset form internally and update formState accordingly.

    • promise will only be resolved once during useForm() call
    • It's possible to supply resetOptions as well
    const { formState: { isLoading } } = useForm({
      defaultValues: fetch('API')
      // resetOptions: {
      //   keepDirtyValues: true
      // }
    })
    

    React use API

    useForm({
      defaultValues: use(fetch('API'))
      // resetOptions: {
      //   keepDirtyValues: true
      // }
    })
    

    https://user-images.githubusercontent.com/10513364/208200735-6248b069-9b7d-4bd1-9742-55d1ef8d238a.mov

    ๐Ÿ™‹ What's the difference between values and defaultValues

    values will react to changes and reflect on the form values, and defaultValues is cached for once and will never re-run the promise or react to defaultValues changes.

    โณ close #9525 add isLoading state for async defaultValues (#9526) ๐Ÿž fix #9581 incorrect type for array of string for message (#9584) ๐Ÿž fix #9571 validation issue with unregister input with valueAsNumber (#9572) ๐Ÿž fix(useWatch): default value for array of inputs (#9555) ๐Ÿ“” fix Controller example using deprecated as prop (#9535) ๐Ÿž fix #9521 isValidting property stuck (#9523) ๐Ÿ”จ feat: Migrate to pnpm (#9516) ๐ŸŽน fix #9509 incorrect type for WatchObserver (#9510) ๐ŸŒณ include flush root render method to createFormControl (#9479)

    Huge thanks goes to @nvh95's work on PNPM and also thanks to @bell-steven's contribution

    Source code(tar.gz)
    Source code(zip)
  • v7.40.0(Nov 29, 2022)

    ๐Ÿƒ๐Ÿปโ€โ™‚๏ธ close #9454 set isValid and abort early for the error field (#9457)

    • Improved async validation and especially combined with sync ones, which will abort early sync failed first
    • IsValid evaluation will abort early if current field validation failed
    • apply to both build-in and schema valdiation

    https://user-images.githubusercontent.com/10513364/204661619-af11f963-588b-4e15-8699-970e6a40e48b.mov

    ๐Ÿž fix #9473 avoid update isDirty & dirtyFields unless flag is passed down (#9475)

    thanks @blingblingredstar for the verify

    Source code(tar.gz)
    Source code(zip)
  • v7.39.7(Nov 28, 2022)

  • v7.39.6(Nov 27, 2022)

    ๐Ÿš€ fix fieldArray changes only notify relevant subscribers (#9448) ๐Ÿชถ improve useFormContext perf by avoid reference re-create with omit ( #9407) ๐Ÿ’†๐Ÿป fix potential watch() global state overwrite (#9450) ๐Ÿฆ close #9410 improve UX when subscribe to both isValid and errors state (#9413) ๐Ÿฅจ added eslint rule for no-extra-boolean-cast (#9449)

    thanks to @elton-okawa

    Source code(tar.gz)
    Source code(zip)
  • v7.40.0-next.1(Nov 23, 2022)

    ๐Ÿ‘ Improved async defaultValues inference

    const fetchData = async () => {
      await sleep(1000)
      return {
        data: 'test'
      }
    }
    
    - useForm<Awaited<ReturnTypeof<typeof fetchData>>>({
    + useForm({
      defaultValues: fetchData, // will infer the promise return type
    })
    

    ๐Ÿ‘ Improved useForm resetOptions to keep track of dirty input

    - const { formState: { dirtyFields } } = useForm({
    + useForm({ // dirtyFields subscription is no longer required
      values,
      resetOptions: {
        keepDirtyValues; true, // only non dirty input will receive data from the values update
      }
    })
    

    ๐Ÿชถ improve useFormContext perf by avoiding reference re-create with omit ๐Ÿฆ close #9410 improve UX when subscribing to both isValid and errors state (#9413)

    Source code(tar.gz)
    Source code(zip)
  • v7.39.5(Nov 21, 2022)

    ๐Ÿ„ upgrade to TS4.9 (#9371) ๐Ÿž fix #9383 always updates the errors state for the field array even when the errors subscription missing (#9384) ๐ŸŒป close https://github.com/react-hook-form/react-hook-form/issues/9379 flush extra re-render to update the current form state subscription ๐Ÿฅฝ improve watch logic (#9397) ๐Ÿ”จ fix conditional useFormState test (#9388)

    thanks to @romain-trotard

    Source code(tar.gz)
    Source code(zip)
  • v7.40.0-next.0(Nov 17, 2022)

    ๐Ÿ‘‰ NEW values props

    The following syntax will react to values prop update/changes.

    • values will be reactive to update/change and reset accordingly
    • provide a reset option to keep dirty/touched values potentially
    const values = await fetch('API')
    
    useForm({
      values, // will reset the form when values updates
      // resetOptions: {
      //   keepDirtyValues: true
      // }
    })
    

    ๐Ÿ‘‰ NEW async defaultValues props

    The following syntax will support async defaultValues, so we will manage the reset form internally and update formState accordingly.

    • promise will only be resolved once during useForm() call
    • It's possible to supply resetOptions as well
    useForm({
      defaultValues: fetch('API')
      // resetOptions: {
      //   keepDirtyValues: true
      // }
    })
    

    React use API

    useForm({
      defaultValues: use(fetch('API'))
      // resetOptions: {
      //   keepDirtyValues: true
      // }
    })
    

    ๐Ÿ™‹ What's the difference between values and defaultValues

    values will react to changes and reflect on the form values, and defaultValues is cached for once and will never re-run the promise or react to defaultValues changes.

    ๐ŸŒป close #9379 flush extra re-render at useFormState to update current form state subscription (#9380) ๐Ÿ„ upgrade to TS4.9 (#9371)

    Source code(tar.gz)
    Source code(zip)
  • v7.39.4(Nov 14, 2022)

  • v7.39.3(Nov 10, 2022)

  • v7.39.2(Nov 9, 2022)

    โŒจ๏ธ close #9339 objects of validation rules type (#9341) ๐Ÿฅธ related #9310 regression to include actual ref instead custom object ( #9312)

    Source code(tar.gz)
    Source code(zip)
  • v7.39.1(Nov 2, 2022)

  • v7.39.0(Nov 1, 2022)

    ๐Ÿ”ฎ improve #8601 and remove the relationship between isValid state with mode (#9219)

    https://user-images.githubusercontent.com/10513364/199356486-bec6cff7-0c33-4076-a60a-e15dc86ddb8a.mov

    ๐Ÿž fix #9282 regression on async validation block validation (#9286) ๐Ÿž fix #9251 isValidating state stale with resolver (#9254) ๐Ÿ delete dirty fields node instead of marking as false (#9156) ๐Ÿคฏ use input reference instead custom object (#9132) ๐ŸฅŠ improve native reset API invoke (#9293) ๐Ÿฆ˜ related #9290 improve setCustomValidity logic (#9292) ๐Ÿ‘บ fix re-render bug with isValid (#9307)

    Source code(tar.gz)
    Source code(zip)
  • v7.38.0(Oct 18, 2022)

    ๐Ÿ•ฐ support validation for week and time input type (#9189)

    <input
      {...register("week", { min: "2022-W40", max: "2022-W50" })}
      type="week"
    />
    <input
      {...register("time", { min: "11:00", max: "12:00" })}
      type="time"
    />
    

    https://user-images.githubusercontent.com/10513364/196547407-8ea7363c-44b8-463e-9aaf-f946a2e5af88.mov

    ๐Ÿง˜๐Ÿป enable focus error with disabled inputs while submitting (#9155) ๐Ÿงฑ prevent runtime error startsWith called with undefined (#9223) ๐Ÿž fix #9216 isValid state not update with async form level trigger (#9218) ๐Ÿงฆ fix accessibility issue on examples with input missing id (#9174) ๐Ÿš” check field array value type before updating (#9170) ๐Ÿ““ update TSDoc for useFieldArray (#9178)

    thanks to @BogdanCerovac and @leapful

    Source code(tar.gz)
    Source code(zip)
  • v7.37.0(Oct 6, 2022)

    ๐Ÿจ feature: include defaultValues inside formState (#8966)

    const { formState, watch } = useForm({
      defaultValues: { name: 'test' }
    })
    const { defaultValues } = useFormState()
    
    const name = watch('name')
    
    return (
      <div>
        <p>Your name was {defaultValues.name}</p>
        <p>Updated name is {name}</p>
      </div>
    )
    

    https://user-images.githubusercontent.com/10513364/194426053-454e8e5b-f1c1-4a9d-8428-ac33296c813f.mov

    ๐Ÿ–จ close #9058 avoid clone object when contains prototype methods

    class DataModel {
      constructor() {
        this.firstName = null
      }
    }
    const formData = new DataModel({ firstName: "Bob" })
    
    useForm({
      defaultValues: formData // no longer get clone internally
    })
    

    ๐Ÿž fix #9134 useFieldArray validation action inconsistency (#9136) ๐Ÿฅท close #9126 useController ref overwrite under strict mode (#9130) ๐Ÿ˜ตโ€๐Ÿ’ซ close #9105 improve input focus method check (#9109) ๐Ÿ“– fix UseFieldArrayAppend types example (#9093) ๐Ÿ–‡ change link (#9159) ๐Ÿ™Œ improve naming of options forEach local (#9152)

    thanks to @arieloO @Ilaygoldman and @simenbrekken-visma

    Source code(tar.gz)
    Source code(zip)
  • v7.37.0-next.0(Sep 29, 2022)

    ๐Ÿจ feature: include defaultValues inside formState (#8966)

    const { formState, watch } = useForm({
      defaultValues: { name: 'test' }
    })
    const { defaultValues } = useFormState()
    
    const name = watch('name')
    
    return (
      <div>
        <p>Your name was {defaultValues.name}</p>
        <p>Updated name is {name}</p>
      </div>
    )
    

    ๐Ÿ˜ตโ€๐Ÿ’ซ close #9105 improve input focus method check (#9109) ๐Ÿ–จ close #9058 avoid clone object when contains prototype methods

    class DataModel {
      constructor() {
        this.firstName = null
      }
    }
    const formData = new DataModel({ firstName: "Bob" })
    
    useForm({
      defaultValues: formData // no longer get clone internally
    })
    

    ๐Ÿ“– fix UseFieldArrayAppend types example (#9093)

    thanks to @arieloO

    Source code(tar.gz)
    Source code(zip)
  • v7.36.1(Sep 23, 2022)

    ๐Ÿชฒ fix #9082 inconsistency between single/group of checkboxes disabled check state (#9083) ๐ŸŒก๏ธ improve setFocus to prevent throw error (#9081)

    Source code(tar.gz)
    Source code(zip)
  • v7.36.0(Sep 20, 2022)

    ๐Ÿš‚ feature: reset to support callback syntax (#9051)

    reset with partial form values will require invoking getValues at the same time, here is an improvement ๐Ÿ‘‡

    Convert your code from:

    reset({
      ...getValues(),
      partialData: 'onlyChangeThis'
    })
    

    to:

    reset((formValues) => {
      return {
        ...formValues,
        partialData: 'onlyChangeThis'
      }
    })
    
    Source code(tar.gz)
    Source code(zip)
  • v7.35.0(Sep 9, 2022)

    ๐ŸŽ‰ feature: new type FieldPathByValue field path by value generic implementation

    function CustomFormComponent<
      TFieldValues extends FieldValues,
      Path extends FieldPathByValue<TFieldValues, Date>
    >({ control, name }: { control: Control<FieldValues>; name: Path }) {
      const { field } = useController({
        control,
        name,
      });
    }
    
    function App() {
      const { control } = useForm<{
        foo: Date;
        baz: string;
      }>();
    
      return (
        <form>
          <CustomFormComponent control={control} name="foo" /> {/* no error */}
          <CustomFormComponent control={control} name="baz" /> {/*  throw an error since baz is string */}
        </form>
      );
    }
    

    ๐Ÿ›ต close #8969 improve type for useFieldArray rules validate prop #8974

    image

    ๐Ÿ›— upgrade to TS 4.8.0 and Jest 29 #8620 ๐Ÿž fix #8970 register field array cause render issue #8972 ๐Ÿž fix: typings for useWatch() with no arguments #8923 ๐Ÿž fix #8919 make useController fieldState properties enumerable

    const { fieldState } = useController({ name: 'test' })
    const copy = {...fieldState} โœ…
    

    ๐Ÿ‘ถ๐Ÿป close #8909 form context children prop type (https://github.com/react-hook-form/react-hook-form/pull/8910)

    <FormProvider {...methods}>
      <div /> // โœ…
      <div /> // โœ…
    </FormProvider>
    

    ๐ŸŒ allow field errors to escape type check when provided with any type ๐Ÿ” github workflows security hardening #8965 ๐Ÿ’š ci: stop csb ci from publishing a comment on PR (https://github.com/react-hook-form/react-hook-form/pull/8977)

    thanks to @Moshyfawn, @sashashura, @carvalheiro, @chetvishal and @MicaelRodrigues

    Source code(tar.gz)
    Source code(zip)
  • v7.35.0-next.0(Aug 25, 2022)

    ๐ŸŽ‰ feature: new type FieldPathByValue field path by value generic implementation

    function SomeCustomFormComponent<
      TFieldValues extends FieldValues,
      Path extends FieldPathByValue<TFieldValues, Date>
    >({ control, name }: { control: Control<FieldValues>; name: Path }) {
      const { field } = useController({
        control,
        name,
      });
      return null;
    }
    
    function ExampleOfUsage() {
      const { control } = useForm<{
        foo: Date;
        baz: string;
      }>();
    
      return (
        <div>
          <SomeCustomFormComponent control={control} name="foo" />{" "}
          {/* throw no error */}
          <SomeCustomFormComponent control={control} name="baz" />{" "}
          {/*  throw an error since baz is string */}
        </div>
      );
    }
    

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8919 make useController fieldState properties enumerable

    const { fieldState } = useController({ name: 'test' })
    const copy = {...fieldState} โœ…
    

    ๐Ÿ‘ถ๐Ÿป close https://github.com/react-hook-form/react-hook-form/issues/8909 form context children prop type (https://github.com/react-hook-form/react-hook-form/pull/8910)

    <FormProvider {...methods}>
      <div /> // โœ…
      <div /> // โœ…
    </FormProvider>
    

    ๐ŸŒ allow field errors to escape type check when provided with any type

    thanks to @carvalheiro, @chetvishal and @MicaelRodrigues

    Source code(tar.gz)
    Source code(zip)
  • v7.34.2(Aug 15, 2022)

  • v7.34.1(Aug 12, 2022)

    ๐Ÿž fix(path): keys of Date | FileList | File shouldn't be add to the PathImpl https://github.com/react-hook-form/react-hook-form/pull/8804 ๐Ÿž fix Date, FileList, File and Blob FieldErrors mapping #8772 ๐ŸšŒ update isSubmitting state after valid form #8829

    function App() {
      const { formState: { isSubmitting }, register } = useForm()
    
      console.log(isSubmitting) // isSubmitting will remain false if form is invalid during submission
    
      return <form onSubmit={handleSubmit(async () => await sleep(1000))}>
        <input {...register('test', { required: true })} />
      </form>
    }
    

    ๐Ÿงƒ upgrade to cypress 10 #8769 ๐Ÿ“– fix nested fields example #8840 ๐Ÿ“– add nested form example #8703 ๐Ÿ“– improve doc of single watch #8773 ๐Ÿ“– fixing typo (Contruรญdo to Construรญdo) on pt-BR translation #8762

    thanks to @HarmonyEarth, @yleflour, @glekner, @vemoo, @ronny1020 and @joaoeffting

    Source code(tar.gz)
    Source code(zip)
  • v7.34.0(Jul 28, 2022)

    ๐ŸŽ‰ feature request: #6879 useFieldArray support rules props (#8102)

    useFieldArray({
      name: 'test',
      rules: {
        required: true,
        minLength: 2,
        maxLength: 10,
        validate: (fieldArrayValues) => {
          if (fieldArrayValues[2].title === 'test') {
            return 'validate Error'
          }
        }
      }
    })
    
    errors?.test?.root?.message // access root level errors
    

    Note: Related context and poll for error message naming: https://github.com/react-hook-form/react-hook-form/discussions/8625

    ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8584: handle nullable nested properties (https://github.com/react-hook-form/react-hook-form/pull/8699) ๐Ÿ†Ž close https://github.com/react-hook-form/react-hook-form/issues/8689 fix type inconsistency with control (https://github.com/react-hook-form/react-hook-form/pull/8691) ๐Ÿž fix native form reset isn't executed if first fieldReference isn't a HTMLElement (https://github.com/react-hook-form/react-hook-form/pull/8678) ๐Ÿž fix useFieldArray action type incorrectness (https://github.com/react-hook-form/react-hook-form/pull/8660) ๐Ÿš” close https://github.com/react-hook-form/react-hook-form/issues/8653 when useFormContext provide no generic for type check (https://github.com/react-hook-form/react-hook-form/pull/8654) ๐Ÿ›ฐ useFormContext include type tests (https://github.com/react-hook-form/react-hook-form/pull/8656) ๐Ÿคฃ fix typo in useForm.ts (https://github.com/react-hook-form/react-hook-form/pull/8645) ๐Ÿ“š README Helper / Sponsor Generation Script / Workflow (https://github.com/react-hook-form/react-hook-form/pull/8676)

    thanks to @@ANTARES-KOR @zandowc @@alexviar @ElectronicsArchiver and @kyoto7250

    Source code(tar.gz)
    Source code(zip)
  • v7.34.0-next.0(Jul 10, 2022)

    ๐ŸŽช feature request: #6879 useFieldArray support rules props (#8102)

    useFieldArray({
      name: 'test',
      rules: {
        required: true,
        minLength: 2,
        maxLength: 10,
        validate: (fieldArrayValues) => {
          if (fieldArrayValues[2].title === 'test') {
            return 'validate Error'
          }
        }
      }
    })
    
    errors?.test?.root?.message // access root level errors
    

    Note: Related context and poll for error message naming: https://github.com/react-hook-form/react-hook-form/discussions/8625

    Source code(tar.gz)
    Source code(zip)
  • v7.33.1(Jul 1, 2022)

    ๐Ÿ fix https://github.com/react-hook-form/react-hook-form/issues/8584: field errors type with optional fields (https://github.com/react-hook-form/react-hook-form/pull/8591) ๐Ÿงณ close https://github.com/react-hook-form/react-hook-form/issues/8600 update code example for NestedValue input ๐Ÿ–ผ Integrate jest-preview into react-hook-form (https://github.com/react-hook-form/react-hook-form/pull/8577) ๐Ÿค“ improve the readability of Merge type (https://github.com/react-hook-form/react-hook-form/pull/8570) ๐Ÿš test: migration from ts-jest to @swc/jest (https://github.com/react-hook-form/react-hook-form/pull/8572) ๐Ÿน refactor: use const instead of props (https://github.com/react-hook-form/react-hook-form/pull/8571) ๐Ÿ” feat: Add ability to search test file on watch mode (https://github.com/react-hook-form/react-hook-form/pull/8573) ๐Ÿง˜๐Ÿป ensure the field is focused when selected (https://github.com/react-hook-form/react-hook-form/pull/8566)

    thanks to @nvh95, @elstgav and @kotarella1110

    Source code(tar.gz)
    Source code(zip)
  • v7.33.0(Jun 24, 2022)

    โš›๏ธ upgrade to react 18 (https://github.com/react-hook-form/react-hook-form/pull/8529) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8558 missing select function for controlled component (https://github.com/react-hook-form/react-hook-form/pull/8559) ๐Ÿ”ฌ improve nested field errors type (https://github.com/react-hook-form/react-hook-form/pull/8527) ๐Ÿ—‘ UseFormHandleSubmit remove unused generic (https://github.com/react-hook-form/react-hook-form/pull/8526)

    ๐Ÿ‘‹ deprecate on NestedValue and UnpackNestedValue (https://github.com/react-hook-form/react-hook-form/pull/8528)

    type FormValues = {
    -  select: NestedValue<{
    -    nested: string
    -  }>
    +  select: {
    +    nested: string
    +  }
    }
    
    errors.select.message โœ… 
    

    Important (25/06/2022)

    The deprecation with UnpackNestedValue caused a breaking change on the @hookform/resolvers package, please refer to the changelog and upgrade the resolver to the latest.

    ๐Ÿฅผ close https://github.com/react-hook-form/react-hook-form/issues/8564 update changelog for breaking change with resolver ๐Ÿ’ฅ The above type deprecation cause breaking change with @hookform/resolvers needs to be upgraded to version ^2.9.3 above

    Huge thanks go to @felixschorer on type improvement and @romain-trotard for improving tests for react 18

    Source code(tar.gz)
    Source code(zip)
  • v7.32.2(Jun 17, 2022)

    ๐Ÿ‹๐Ÿป improve build dist package size (https://github.com/react-hook-form/react-hook-form/pull/8511) ๐Ÿž fix https://github.com/react-hook-form/react-hook-form/issues/8506 delayError not overwrite existing function call (https://github.com/react-hook-form/react-hook-form/pull/8509) ๐Ÿ“– update the use of validadtionSchema in v7 examples (https://github.com/react-hook-form/react-hook-form/pull/8501)

    thanks, @bryantobing12

    Source code(tar.gz)
    Source code(zip)
Owner
React Hook Form
๐Ÿ“‹ React hooks for form validation without the hassle
React Hook Form
๐Ÿ‘ฉโ€๐Ÿณ A React Hooks utility library containing popular customized hooks

React Recipes A React Hooks utility library containing popular customized hooks What's your favorite dish? npm i react-recipes --save yarn add react-r

Craig Walker 931 Dec 28, 2022
๐Ÿน A lot of nice hooks to make react hooks easier to use ( useState callback / life cycle / instance variable)

?? Nice Hooks ไธญๆ–‡็‰ˆ A lot of nice hooks to make react hooks easier to use. If you find this project is useful to you, please give me a star. Installatio

Daniel.xiao 46 Dec 28, 2022
๐Ÿ”ฅ A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development ๐Ÿ”ฅ

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development ?? Live playground here ?? ???? English

Antonio Rรน 6.5k Dec 29, 2022
Learn the more advanced React hooks and different patterns to enable great developer APIs for custom hooks

?? Advanced React Hooks ?? EpicReact.Dev Learn the more advanced React hooks and different patterns to enable great developer APIs for custom hooks. W

Josรฉ Gonรงalves 4 Mar 15, 2022
Use-supabase-hooks contains react hooks for common supabase functions, with type safety!

Use-supabase-hooks contains react hooks for common supabase functions, with type safety!

Anurag 15 Oct 23, 2022
useFormless allow you to control forms in React using react-hook approach

useFormless react-useformless is a simple library that allows you to control forms with react-hooks approach Why useFormless? Works with nested forms

Gibran LM 49 Jul 10, 2022
React validatable form hook that is used to create dynamic client side validations on react forms

React Validatable Form React validatable form hook that is used to create dynamic client side validations on React forms. Table of Contents Install Ge

Open Business Software Solutions 20 Nov 15, 2022
ReactJs Custom hooks, component lifecycle - Indispensable hooks

ReactJs Custom hooks, component lifecycle - Indispensable hooks

Alan Buscaglia 71 Dec 27, 2022
๐Ÿ“„ React hook for managing forms and inputs state

react-use-form-state ?? Table of Contents Motivation Getting Started Examples Basic Usage Initial State Global Handlers Advanced Input Options Custom

Waseem Dahman 941 Dec 8, 2022
React custom hooks for web workers

react-hooks-worker React custom hooks for web workers. Introduction Web Workers are another thread from the main thread in browsers. We can run heavy

Daishi Kato 631 Jan 4, 2023
React hooks web application built as presentation tool for my tech talk, sponsored by SingleSprout.

React Hooks Presentation This react application was built to educate on the basics of React Hooks, and to demonstrate the functionality of 3 primary R

Roland Wynter 5 Jun 28, 2021
A simple Hooks wrapper over Motion One, An animation library, built on the Web Animations API for the smallest filesize and the fastest performance.

A simple Hooks wrapper over Motion One, An animation library, built on the Web Animations API for the smallest filesize and the fastest performance.

Tanvesh Sarve 95 Dec 30, 2022
React Native APIs turned into React Hooks for use in functional React components

React Native Hooks React Native APIs turned into React Hooks allowing you to access asynchronous APIs directly in your functional components. Note: Yo

React Native Community 3k Jan 8, 2023
Travel Website is a React application that uses React Hooks and React Router for this beginner React JS Project

Travel Website is a React application that uses React Hooks and React Router for this beginner React JS Project. The website is fully responsive as well.

Leticia Lumi Nagao 3 Aug 28, 2022
React-cache-api - React Cache API is a React Hooks library for data fetching

React Cache API React Cache API is a React Hooks library for data fetching. It w

awmaker 12 Aug 31, 2022
:tada: React Universal Hooks : just use****** everywhere (Functional or Class Component). Support React DevTools!

react-universal-hooks React Universal Hooks : just use****** everywhere. Support React >= 16.8.0 Installation Using npm: $ npm install --save react-un

Salvatore Ravidร  177 Oct 10, 2022
Lightweight React bindings for MobX based on React 16.8 and Hooks

mobx-react-lite ?? ?? ?? This repo has been moved to mobx This is a lighter version of mobx-react which supports React functional components only and

MobX 2.1k Dec 15, 2022
A delightful modal dialog component for React, built from the ground up to support React Hooks.

?? modali A delightful modal dialog library for React, built from the ground up to support React Hooks. Modali provides a simple interface to build be

Upmostly 205 Nov 23, 2022