Rishabh Guha
Rishabh Guha

Reputation: 77

React too many re-renders error when trying to use 'useState'

I am getting the following error:

enter image description here

This is the component code snippet causing the error:

const EditDetailsModal = ({show, handleClose}) => {

    const name = useSelector(selectors.getName)
    const email = useSelector(selectors.getEmail)
    const phoneNumber = useSelector(selectors.getPhone)
    const country = useSelector(selectors.getCountry)
    const key = "AIzaSyCda4pqQF5xcyDAfA7gt61jVXcaeKeES44";
    const [newName, setNewName] = React.useState();
    setNewName(name);
    function handleChange(e) {
      setNewName(e.target.value);
    }

    return (
          <Modal show={show} onHide={handleClose} className="editModal">
                <FormContainer>
                    <Modal.Header className="editModalHeader" closeButton>
                      <Modal.Title>Edit Personal Details</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Form>
                          <Form.Group controlId="formBasicName">
                            <ModalTextInput customPlaceholder="Name" value={newName} onChange={(event) => handleChange(event)}/>
                          </Form.Group>

Would be grateful if you could help me identify what is causing this.

Upvotes: 1

Views: 53

Answers (2)

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

setNewName(name);
    function handleChange(e) {
      setNewName(e.target.value);
    }

there is no need to call setNewName(name); above the handleChange function. just delete it

Upvotes: 0

Taki
Taki

Reputation: 17654

You're calling setNewName everytime it re-renders, updating newName causing another render, resulting in an infinite re-renders,

remove setNewName call, and set the initial value like React.useState(name);

const [newName, setNewName] = React.useState(name); // set the initial value of newName
    
// setNewName(name); // remove this line
function handleChange(e) {
  setNewName(e.target.value);
}

...

Upvotes: 1

Related Questions