title: how to splice or push new elements in a specific index with usestate?
body: <p>I'm trying to insert new elements in the array and update the state base on the array, but the problem after I update the state It doesn't get rendered in the component.</p>
  <ul>
  <li>note: I'm not really sure how to use splice. ( I wanted the <code>handleClick</code> function to add new element under the clicked element but it seems I failed in that as well.)</li>
  <li>note 2: I also tried <code>setstate((pre) =&gt; { pre.splice(index + 1, 0, { id: 3, text: &quot;xxx&quot;, autoFocus: true }); return pre; }); </code> but didn't work as well.</li>
  </ul>
  <pre><code>import React, { useState } from &quot;react&quot;;
  import &quot;./styles.css&quot;;
  
  export default function App() {
    let elements = [
      { id: 0, text: &quot;first&quot;, autoFocus: true },
      { id: 1, text: &quot;second&quot;, autoFocus: true },
      { id: 2, text: &quot;third&quot;, autoFocus: true }
    ];
    const [state, setstate] = useState(elements);
  
    function handChange(e) {
      if (e.keyCode == 13) {
        const x = state;
        const index = x.findIndex((item) =&gt; item.id == e.target.id);
  
        //i'm using autoFocus to move the focus  (I-beam pointer) to the nex field.
        //but i still get errors with it
        // e.map((item) =&gt; Object.assign(item, { autoFocus: false }));
        
        x.splice(index + 1, 0, { id: 3, text: &quot;xxx&quot;, autoFocus: true });
        console.log(state); // you can see this update probarly
        setstate(x); // but when I update state sometimes it don't render othertimes it take a while before render.
  
      }
    }
  
    return (
      &lt;div className=&quot;App&quot;&gt;
        {state.map((e) =&gt; (
          // when I say it don't render I mean the e value don't get updated.
          &lt;div
            focus={e.focus}
            contentEditable=&quot;true&quot;
            id={e.id}
            onKeyUp={handChange}
          &gt;
            {e.text}
          &lt;/div&gt;
        ))}
      &lt;/div&gt;
    );
  }
  
  </code></pre>
  <p>on <a href="https://codesandbox.io/s/beautiful-silence-c1t1k?file=/src/App.js" rel="nofollow noreferrer">codesandbox</a></p>