question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Generated defaultValues are not applied after first render

See original GitHub issue

I have a form that includes controlled components (several Material-UI checkboxes). By specifying defaultValues, I am able to reset the form successfully. However, if defaultValues changes depending on props, the reset of the controlled components fails.

E.g., this works:

const MyForm = ({ acls }) => {
  ...
  const defaultValues = {
    name: '',
    acls: [false, false, false, false, false, false, false]
  };
  const { handleSubmit, register, errors, reset, setValue, control } = useForm({
    defaultValues
  });
  ...
}

This does not:

const MyForm = ({ acls }) => {
  ...
  const defaultValues = {
    name: '',
    acls: Array(acls.length).fill(false)
  };
  const { handleSubmit, register, errors, reset, setValue, control } = useForm({
    defaultValues
  });
  ...
}

I can see that my top-level component gets re-rendered, as acls changes along the way from 0 to 7 elements. Thus, in the first example, defaultValues is constant, while in the second it is modified because of the props updating. Is it possible that, somehow, useForm is not being executed upon the second render?

My apologies, I am unsure how to build a codesandbox that replicates this behavior. If you have a hint on how to replicate the props update there, I’d be happy to give it a shot.

Expected behavior

When I recreate a form using useForm with different parameters, those parameters should take effect.

Desktop (please complete the following information):

  • OS: Linux
  • Browser: Firefox
  • Version: 73
  • react-hook-form: 5.6.1

Thank you very much for react-hook-form. I really like what I’m seeing so far!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:26 (13 by maintainers)

github_iconTop GitHub Comments

2reactions
stefanvcommented, May 7, 2020

I’m including the full example here for posterity, in case the code sandbox goes away. The reason I did not use useFieldArray is because, in my actual example, I had a more complex form to set up.

What is simulated here is a component that generates a dynamic Material-UI form, based on incoming props.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm, Controller } from "react-hook-form";

import { Checkbox } from "@material-ui/core";

const Form = ({ nr }) => {
  nr = parseInt(nr, 10);

  const { handleSubmit, reset, control } = useForm();

  const onSubmit = data => {
    console.log("Submit with:", data);
    reset();
  };

  useEffect(() => {
    reset({
      checkbox: Array(nr).fill(false)
    });
  }, [reset, nr]);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {Array.from(Array(nr).keys()).map(x => (
        <div>
          Item {x}
          <Controller
            as={Checkbox}
            key={x}
            name={`checkbox[${x}]`}
            control={control}
            defaultValue={false}
          />
        </div>
      ))}
      <button type="submit">Submit & reset</button>
    </form>
  );
};

const VariableForm = () => {
  let [nr, setNr] = useState("1");

  const onInput = event => {
    setNr(parseInt(event.target.value, 10));
  };

  return (
    <div>
      <p>Increase the counter below to build a larger form.</p>

      <input type="number" name="count" defaultValue="1" onInput={onInput} />
      <Form nr={nr} />
    </div>
  );
};

function App() {
  return VariableForm();
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
2reactions
bluebill1049commented, May 4, 2020

where is the codesandbox to reproduce? if your defaultValues is changing, then you will need to use reset().

Reason: we do cache defaultValues inside the hook, otherwise you will have to memo the value yourself which is not great DX.

Screen Shot 2020-05-04 at 10 50 50 am

I have an issue to update FAQ to include this as well.

Read more comments on GitHub >

github_iconTop Results From Across the Web

DefaultValues of react-hook-form is not setting the values to ...
The problem is that during the first render, users is the useState hook's initial value, which is null . The value only changes...
Read more >
useForm - watch - Simple React forms validation
When defaultValue is not defined, the first render of watch will return undefined because it is called before register . It's recommend to...
Read more >
Using localStorage with React Hooks - LogRocket Blog
Initial localStorage project setup. Working with a fresh React application, let's head over to the computer terminal and run the following ...
Read more >
A Complete Guide to Testing React Hooks - Toptal
In this article, we will see how we can test this hook, first using no test ... on re-render // we can also...
Read more >
Docs • Svelte
With this, npm run build will generate HTML, JS and CSS files inside the dist directory. ... By default intro transitions will not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found