title: Removing items from state by timer
body: <p>There is a local state (hook), it has an array of four elements. There is a button on the screen to add a new element to this array. When a component is loaded, in useEffect called method that removes the first element from the state every 5 seconds. If you do not touch the button that adds a new element to the state, then everything works great. But if you start adding elements, the deletion works according to the previous state, only then the state with the new element is displayed. Tell me how to fix it so that everything works stably. I understand what needs to be sought in the direction of the life cycle, a conflict of states occurs, but I can not find a solution.</p>
  
  <pre><code>const Component = () =&gt; {
  
      const [arr, setArr] = useState(['one', 'two', 'three', 'four']);
  
      React.useEffect(() =&gt; {
          console.log("render");
          setTimeout(deleteElementFromArr, 5000)
      });
  
      const addNewElementToArr = () =&gt; {
          let temp = arr.slice();
          temp.push('newElement');
          setArr(temp);
      };
  
      const deleteElementFromArr = () =&gt; {
          if (arr.length &gt; 0) {
              console.log(arr);
              let temp = arr.slice();
              temp.splice(0, 1);
              setArr(temp)
  
          }
      };
  
      return (&lt;div&gt;
          &lt;div&gt;
              &lt;Button onClick={addNewElementToArr}&gt;add&lt;/Button&gt;
          &lt;/div&gt;
          &lt;div style={{margiTop: '10px'}}&gt;
              {arr.map(a =&gt; `${a} `)}
          &lt;/div&gt;
      &lt;/div&gt;)
  };
  </code></pre>
  
  <p><a href="https://codepen.io/slava4ka/pen/WNNvrPV" rel="nofollow noreferrer">https://codepen.io/slava4ka/pen/WNNvrPV</a></p>