title: Deleting items from an array React (infinite re-render loop error)
body: <p>In a small React app, I'm trying to add delete functionality via a button for a list. Presently, I'm attempting this through the deleteItem function, which makes use of array.splice prototype method.</p>
  <p>However, I'm encountering the error, <code>Too many re-renders. React limits the number of renders to prevent an infinite loop.</code>. What is the cause of this error? Shouldn't this function only be invoked once, when the button is clicked?</p>
  <p>And how can I resolve this error?</p>
  <pre><code>import &quot;./styles.css&quot;;
  import React, { useState, Fragment } from &quot;react&quot;;
  
  export default function App() {
    const [items, setItems] = useState([&quot;first item&quot;]);
    const [newItem, setNewItem] = useState(&quot;&quot;);
  
    const handleSubmit = (event) =&gt; {
      event.preventDefault();
      setItems([newItem, ...items]);
    };
  
    const handleChange = (event) =&gt; {
      setNewItem(event.target.value);
    };
  
    const deleteItem = (i) =&gt; {
      setItems(items.splice(i,1))
    }
  
    return (
      &lt;div&gt;
        &lt;form&gt;
          &lt;input type=&quot;text&quot; value={newItem} onChange={handleChange} /&gt;
          &lt;input type=&quot;button&quot; value=&quot;submit&quot; onClick={handleSubmit} /&gt;
        &lt;/form&gt;
        &lt;ul&gt;
          {items.map((i) =&gt; {
            return (
            &lt;Fragment&gt;
              &lt;li&gt;{i}&lt;/li&gt;
                &lt;button
                  onClick= {() =&gt; deleteItem(i)}&gt; // Amr recommendation
                  delete 
                &lt;/button&gt;
            &lt;/Fragment&gt;
            );
          })}
        &lt;/ul&gt;
      &lt;/div&gt;
    );
  }
  
  </code></pre>
  <p>Edit: I've taken user, Amr's, recommendation and added a anonymous arrow function to the button. However, a new issue has arisen. I can delete any item up until there exists only one item in the array. The final item cannot be deleted. Why is this?</p>