Next.js Discord

Discord Forum

Why the component is re-rendering on every keystroke

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
        const {
          firstname,
          setFirstname,
          lastname,
          setLastname,
         } = useZustandState();

        console.log('re-render')
        return (
              <form
                className="space-y-8"
              >
                <div className=" flex gap-3 px-3">
                  <div className="flex flex-col gap-2">
                    <Label>First name(s)</Label>
                    <Input
                      placeholder="firstname"
                      value={firstname}
                      onChange={(e) => setFirstname(e.target.value)}
                      className="truncate"
                    />
                  </div>

                  <div className="flex flex-col gap-2">
                    <Label>Last name</Label>
                    <Input
                      placeholder="lastname"
                      value={lastname}
                      onChange={(e) => setLastname(e.target.value)}
                      className="truncate"
                    />
                  </div>
                </div>
            </form>
            )

4 Replies

American black bearOP
How can I implement debounce is this component ?
American Crow
If you want to get sophisticated with forms, you prob. want to use a form library like react-hook-form which internally uses useRef instead of useState for managing Form Fields, to avoid re-renders as much as possible.
American black bearOP
@American black bear I was using react-hook-form but the want the state of firstname and lastname to show on side view when its changes, I was using form.watch to keep track the state.
what I want is to implement debounce like thing to prevent from re-render a lot
American Crow
In that case you probably want to use the built in useFormContext and somth. like
const { getValues } = useFormContext()
const firstname = getValues("firstName")
const lastname = getValues("lastName")
within your side view component

If you insist on debouncing, personally i'd use somth. like
https://mantine.dev/hooks/use-debounced-value/