Home > Back-end >  How to set a state inside form without re-render component
How to set a state inside form without re-render component

Time:03-17

I've got a form, where I wanna set in the state (setEducation for example) incoming value from the input. I use onChange, but this causes the component to be rendered each time I make a change to the input field. What is the right way to fix the problem?

<form id="loginform" onSubmit={onBecomeDoctorRequestHandler} >
                                <div className="form-group mb-3">
                                    <label>Education</label>
                                    <input
                                        type="text"
                                        className="form-control"
                                        required
  this onChange causes the              placeholder="Harvard"
  component to be rendered              onChange={(event) => setEducation(event.target.value.trim())}
                                    />
                                    <small className="text-danger form-text">
                                        {educationError}
                                    </small>
                                </div>

CodePudding user response:

As-is all your form elements will re-render when any form element changes because the "value" of onClick is a new function each time the component runs (renders).

To fix that, wrap the onClick function in a useCallback. The useCallback will preserve the "value" of the function across renders, so only the elements that needs to be re-rendered will be.

  • Related