title: Setting state along with AsyncStorage in useEffect hook causes infinite loop?
body: <p>I'm new to <code>hooks</code> and recently started using hooks in my React Native projects.</p>
  
  <p>I'm building a simple todo app using the <code>AsyncStorage</code>. First I initialize initial <code>data</code> and <code>setData</code> state using <code>useState</code> hook:</p>
  
  <pre><code>const [data, setData] = useState([]);
  </code></pre>
  
  <p>There are two <code>textInput</code> and submit button that I use to save data to AsyncStorage. Here is the <code>saveData</code> function:</p>
  
  <pre><code>const saveData = async () =&gt; {
    const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput
  
    const storedData = await AsyncStorage.getItem('user');
    const storedDataParsed = JSON.parse(storedData);
  
    let newData = [];
  
    if (storedData === null) {
      // save
      await AsyncStorage.setItem('user', JSON.stringify(arrData));
    } else {
      newData = [...storedDataParsed, user];
      await AsyncStorage.setItem('user', JSON.stringify(newData));
    }
    setName('');
    setPhone('');
    Keyboard.dismiss();
  };
  </code></pre>
  
  <p>Now, I'm using <code>useEffect</code> to get data from the AsyncStorage and setting it to the <code>data</code> state. I'm using data to render the text in the screen.</p>
  
  <pre><code>useEffect(() =&gt; {
    retrieveData();
  }, [data]);
  
  const retrieveData = async () =&gt; {
    try {
      const valueString = await AsyncStorage.getItem('user');
      const value = JSON.parse(valueString);
      setData(value);
    } catch (error) {
      console.log(error);
    }
  };
  </code></pre>
  
  <p>I'm using <code>[data]</code> in useEffect since I want to re-render my component each time  data changes i.e. each time I save data in AsyncStorage. But this is causing infinite loop as <code>setData</code> causes useEffect to run infinitely.</p>
  
  <p>If I remove <code>data</code> from the <code>[]</code> it doesn't loop but my data in render is one step behind. So whenever I save data it doesn't show the current data but the previous one.</p>
  
  <p>Any explanation of what I am doing wrong here and how can i fix this?</p>
  
  <p>Thanks.</p>