skip to Main Content

So here is my code,

When ever I click the Add to list button the page is being re rendered several times.

I know it’s something to do with react hook forms, because if I move the button outside the form it doesn’t do it.

I’m trying to call setBannersDataList but this doesn’t work outside the react hook form, only works with the button inside the form.

Any help?

'use client';

import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from './ui/button';
import { SubmitHandler, UseFormRegister, UseFormReturn, UseFormSetValue, set, useForm } from 'react-hook-form';
import { Form, FormControl, FormField, FormItem, FormLabel } from './ui/form';


export default function Component({ details }: EditorProps) {
  const [bannersDataList, setBannersDataList] = useState<any>([]);
 

  const onSubmit: SubmitHandler<any> = (data) => console.log(data);

  const form = useForm<any>();

  const {
    register,
    setValue,
    handleSubmit,
    watch,
    getValues,
    formState: { errors },
  } = form;


  console.log('boo');

  return (
        <Form {...form}>
          <form className="grid w-full items-start gap-6" onSubmit={handleSubmit(onSubmit)}>
                <FormField
                  control={form.control}
                  name="size"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Sizes</FormLabel>
                      <FormControl>
                        <Select
                          {...field}
                          defaultValue="300x250"
                        >
                          <SelectTrigger id="size" className="items-start [&_[data-description]]:hidden">
                            <SelectValue placeholder="Select a size" />
                          </SelectTrigger>
                          <SelectContent>
                            {details.sizes?.map((size) => (
                              <SelectItem value={size} key={size}>
                                {size}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </FormControl>
                    </FormItem>
                  )}
                />
            <Button
              onClick={() => {
               // click this causes the component to re-render loads of times even
               // boo is consoled logged out like 20 times when I click this button
              }}
            >
              Add banner to list
            </Button>
          </form>
        </Form>
  );
}

What I am expecting is that when I click on Add banner to list button and call setBannersDataList, the component doesn’t re render so many times.

2

Answers


  1. The reason maybe is that the button clicking also triggers default behaviour of form to be submitted when the button is clicked. that’s why it is not re-rendering the form when you moved the button outside the form.

    Another method you can implement is to add a line in the onClick callback(e.preventDefault()), here is the code for button while keeping it inside form,

    <Button
      onClick={(e) => {
        e.preventDefault(); // new line added
        // your further logic
      }}
    >
      Add banner to list 
    </Button>
    
    Login or Signup to reply.
  2. It seems like the issue you’re facing is related to the re-rendering of your component triggered by the onClick event of the button inside the form. This behavior is likely to be caused by the interaction between React Hook Form and your component’s state updates. One possible solution is to prevent the default behavior of the button’s onClick event, which could be causing the form to submit and trigger a re-render. You can achieve this by calling event.preventDefault() inside the onClick handler. Here’s how you can modify your button’s onClick handler:

    <Button
      onClick={(event) => {
        event.preventDefault(); // Prevent default form submission
        // Your logic here
      }}
    >
      Add banner to list
    </Button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search