title: Why the state of a useState snaps back to false if I go back and forth on the Screen?
body: <p>I've been trying to toggle favorite products and store their <code>id</code> and an <code>isFav</code> prop on a Firebase database. Then I use them to show the favorites on the <code>FavoritesScreen</code>. </p>
  
  <p>If I go to the <code>ProductDetailsScreen</code> (where I toggle the favorite) I toggle it true/false with no problem. </p>
  
  <p>Further if I then use the <code>Bottom Tab Navigation</code> to check the <code>FavoritesScreen</code> or the <code>OrdersScreen</code> etc and then go back to <code>ProductDetailsScreen</code>, nothing is changed.</p>
  
  <p><strong>But</strong> if (from the <code>ProductDetailsScreen</code>) I go back (to <code>ProductsOverviewScreen</code>) and then come back again on <code>ProductDetailsScreen</code> the state of <code>isFav</code>
  snaps back to false! Nevertheless the <code>id</code> and <code>isFav</code> are saved on Firebase, but <code>isFav</code> is saved as <code>false</code>.</p>
  
  <p>Note: I use a useState() hook...</p>
  
  <p>One more thing that I don't understand happens when I  try to log <code>isFav</code>. 
  I have two logs, one inside the <code>toggleFavoriteHandler</code> and one outside. When I <strong>first</strong> run the <code>toggleFavoriteHandler</code>, where I also have <code>setIsFav(prevState =&gt; !prevState);</code> I get:
  Output:</p>
  
  <p><code>outside: false
  inside: false
  outside: true</code></p>
  
  <p>So I guess the first two false are from the initial state and then the true is from the above state-toggling. But why it gets it only outside true? Why actually the first two are false? I change the state to true before the log. I would expect it to immediately change to true and have them all true! </p>
  
  <p>Then if I go back to <code>ProductsOverviewScreen</code> and then again to <code>ProductDetailsScreen</code> I get two logs from outside:</p>
  
  <p>Output:</p>
  
  <p><code>outside: true
  outside: false</code></p>
  
  <p>So it snaps back to its initial state! ?</p>
  
  <p>I really do not understand how the work-flow goes. Are these logs normal?</p>
  
  <p>Can anybody give some hints where the bug from going back and forth could be, please?</p>
  
  <p>Thanks!</p>
  
  <p>Here is the code:</p>
  
  <p><strong>ProductDetailsScreen.js</strong></p>
  
  <pre><code>...
  
  const ProductDetailScreen = (props) =&gt; {
      const [ isFav, setIsFav ] = useState(false);
      const dispatch = useDispatch();
  
      const productId = props.navigation.getParam('productId');
      const selectedProduct = useSelector((state) =&gt;
          state.products.availableProducts.find((prod) =&gt; prod.id === productId)
      );
  
  
  
      const toggleFavoriteHandler = useCallback(
          async () =&gt; {
              setError(null);
              setIsFav((prevState) =&gt; !prevState);
              console.log('isFav inside:', isFav); // On first click I get: false
              try {
                  await dispatch(
                      productsActions.toggleFavorite(
                          productId,
                          isFav,
                      )
                  );
              } catch (err) {
                  setError(err.message);
              }
          },
          [ dispatch, productId, isFav setIsFav ]
      );
      console.log('isFav outside: ', isFav); // On first click I get: false true
  
      return (
          &lt;ScrollView&gt;
              &lt;View style={styles.icon}&gt;
                  &lt;TouchableOpacity style={styles.itemData} onPress={toggleFavoriteHandler}&gt;
                      &lt;MaterialIcons name={isFav ? 'favorite' : 'favorite-border'} size={23} color="red" /&gt;
                  &lt;/TouchableOpacity&gt;
              &lt;/View&gt;
              &lt;Image style={styles.image} source={{ uri: selectedProduct.imageUrl }} /&gt;
              {Platform.OS === 'android' ? (
                  &lt;View style={styles.button}&gt;
                      &lt;CustomButton
                          title="Add to Cart"
                          onPress={() =&gt; dispatch(cartActions.addToCard(selectedProduct))}
                      /&gt;
                  &lt;/View&gt;
              ) : (
                  &lt;View style={styles.button}&gt;
                      &lt;Button
                          color={Colours.gr_brown_light}
                          title="Add to Cart"
                          onPress={() =&gt; dispatch(cartActions.addToCard(selectedProduct))}
                      /&gt;
                  &lt;/View&gt;
              )}
  
              &lt;Text style={styles.price}&gt;€ {selectedProduct.price.toFixed(2)}&lt;/Text&gt;
              &lt;Text style={styles.description}&gt;{selectedProduct.description}&lt;/Text&gt;
          &lt;/ScrollView&gt;
      );
  };
  
  ProductDetailScreen.navigationOptions = ({ navigation }) =&gt; {
      return {
          headerTitle: navigation.getParam('productTitle'),
          headerLeft: (
              &lt;HeaderButtons HeaderButtonComponent={CustomHeaderButton}&gt;
                  &lt;Item
                      title="goBack"
                      iconName={Platform.OS === 'android' ? 'md-arrow-back' : 'ios-arrow-back'}
                      onPress={() =&gt; navigation.goBack()}
                  /&gt;
              &lt;/HeaderButtons&gt;
          ),
          headerRight: (
              &lt;HeaderButtons HeaderButtonComponent={CustomHeaderButton}&gt;
                  &lt;Item
                      title="cart"
                      iconName={Platform.OS === 'android' ? 'md-cart' : 'ios-cart'}
                      onPress={() =&gt; navigation.navigate({ routeName: 'Cart' })}
                  /&gt;
              &lt;/HeaderButtons&gt;
          )
      };
  };
  ...styles
  </code></pre>
  
  <p><strong>products.js/actions</strong></p>
  
  <pre><code>export const toggleFavorite = (id, isFav) =&gt; {
      return async (dispatch) =&gt; {
          try {
              // If it is a favorite, post it.
              // Note it is initially false... 
              if (!isFav) {
                  const response = await fetch('https://ekthesi-7767c.firebaseio.com/favorites.json', {
                      method: 'POST',
                      headers: {
                          'Content-Type': 'application/json'
                      },
                      body: JSON.stringify({
                          id,
                          isFav
                      })
                  });
  
                  if (!response.ok) {
                      throw new Error(
                          'Something went wrong.'
                      );
                  }
                  const resData = await response.json();
  
                  // Note: No `name` property, that's why we use a `for_in` loop
                  // console.log('POST', JSON.stringify(resData));
  
                  dispatch({ type: TOGGLE_FAVORITE, productId: id });
              } else if (isFav) {
                  // First get the key in order to delete it in second fetch(...).
                  const response = await fetch(`https://ekthesi-7767c.firebaseio.com/favorites.json`);
  
                  if (!response.ok) {
                      throw new Error(
                          'Something went wrong.'
                      );
                  }
  
                  const resData = await response.json();
  
                  // Note: No `name` property, that's why we use a `for_in` loop
                  // console.log('fetch', JSON.stringify(resData));
  
                  for (const key in resData) {
                      console.log('resData[key].id', resData[key].id === id);
                      if (resData[key].id === id) {
                          await fetch(`https:app.firebaseio.com/favorites/${key}.json`, {
                              method: 'DELETE'
                          });
  
                          if (!response.ok) {
                              throw new Error(
                                  'Something went wrong.'
                              );
                          }
                          // console.log('fetch', JSON.stringify(resData));
                          dispatch({ type: TOGGLE_FAVORITE, productId: id });
                      }
                  }
              }
          } catch (err) {
              // send to custom analytics server
              throw err;
          }
      };
  };
  </code></pre>
  
  <p><strong>ProductsOverviewScreen.js</strong></p>
  
  <pre><code>...
  
  const ProductsOverviewScreen = (props) =&gt; {
      const [ isLoading, setIsLoading ] = useState(false);
      const [ error, setError ] = useState(); // error initially is undefined!
      const [ isRefresing, setIsRefresing ] = useState(false);
      const dispatch = useDispatch();
      const categoryId = props.navigation.getParam('categoryId');
      const products = useSelector((state) =&gt;
          state.products.availableProducts.filter((prod) =&gt; prod.categoryIds.indexOf(categoryId) &gt;= 0)
      );
      const productId = props.navigation.getParam('productId');
      const isFav = useSelector((state) =&gt; state.products.favoriteProducts.some((product) =&gt; product.id === productId));
  
  
      const loadProducts = useCallback(
          async () =&gt; {
              setError(null);
              setIsRefresing(true);
              try {
                  await dispatch(productsActions.fetchProducts());
              } catch (err) {
                  setError(err.message);
              }
              setIsRefresing(false);
          },
          [ dispatch, setIsLoading, setError ]
      );
  
      // loadProducts after focusing
      useEffect(
          () =&gt; {
              const willFocusEvent = props.navigation.addListener('willFocus', loadProducts);
              return () =&gt; willFocusEvent.remove();
          },
          [ loadProducts ]
      );
  
      // loadProducts initially...
      useEffect(
          () =&gt; {
              setIsLoading(true);
              loadProducts();
              setIsLoading(false);
          },
          [ dispatch, loadProducts ]
      );
  
      const selectItemHandler = (id, title) =&gt; {
          props.navigation.navigate('DetailScreen', {
              productId: id,
              productTitle: title,
              isFav: isFav
          });
      };
  
      if (error) {
          return (
              &lt;View style={styles.centered}&gt;
                  &lt;Text&gt;Something went wrong!&lt;/Text&gt;
                  &lt;Button title="Try again" onPress={loadProducts} color={Colours.chocolate} /&gt;
              &lt;/View&gt;
          );
      }
  
      if (isLoading) {
          return (
              &lt;View style={styles.centered}&gt;
                  &lt;ActivityIndicator size="large" color={Colours.chocolate} /&gt;
              &lt;/View&gt;
          );
      }
  
      if (!isLoading &amp;&amp; products.length === 0) {
          return (
              &lt;View style={styles.centered}&gt;
                  &lt;Text&gt;No products yet!&lt;/Text&gt;
              &lt;/View&gt;
          );
      }
  
      return (
          &lt;FlatList
              onRefresh={loadProducts}
              refreshing={isRefresing}
              data={products}
              keyExtractor={(item) =&gt; item.id}
              renderItem={(itemData) =&gt; (
                  &lt;ProductItem
                      title={itemData.item.title}
                      image={itemData.item.imageUrl}
                      onSelect={() =&gt; selectItemHandler(itemData.item.id, itemData.item.title)}
                  &gt;
                      {Platform.OS === 'android' ? (
                          &lt;View style={styles.actions}&gt; 
                              &lt;View&gt;
                                  &lt;CustomButton
                                      title="Details"
                                      onPress={() =&gt; selectItemHandler(itemData.item.id, itemData.item.title)}
                                  /&gt;
                              &lt;/View&gt;
                              &lt;BoldText style={styles.price}&gt;€ {itemData.item.price.toFixed(2)}&lt;/BoldText&gt;
                              &lt;View&gt;
                                  &lt;CustomButton
                                      title="Add to Cart"
                                      onPress={() =&gt; dispatch(cartActions.addToCard(itemData.item))}
                                  /&gt;
                              &lt;/View&gt;
                          &lt;/View&gt;
                      ) : (
                          &lt;View style={styles.actions}&gt;
                              &lt;View style={styles.button}&gt;
                                  &lt;Button
                                      color={Colours.gr_brown_light}
                                      title="Details"
                                      onPress={() =&gt; selectItemHandler(itemData.item.id, itemData.item.title)}
                                  /&gt;
                              &lt;/View&gt;
                              &lt;BoldText style={styles.price}&gt;€ {itemData.item.price.toFixed(2)}&lt;/BoldText&gt;
                              &lt;View style={styles.button}&gt;
                                  &lt;Button
                                      color={Colours.gr_brown_light}
                                      title="Add to Cart"
                                      onPress={() =&gt; dispatch(cartActions.addToCard(itemData.item))}
                                  /&gt;
                              &lt;/View&gt;
                          &lt;/View&gt;
                      )}
                  &lt;/ProductItem&gt;
              )}
          /&gt;
      );
  };
  
  ProductsOverviewScreen.navigationOptions = (navData) =&gt; {
      return {
          headerTitle: navData.navigation.getParam('categoryTitle'),
          headerRight: (
              &lt;HeaderButtons HeaderButtonComponent={CustomHeaderButton}&gt;
                  &lt;Item
                      title="cart"
                      iconName={Platform.OS === 'android' ? 'md-cart' : 'ios-cart'}
                      onPress={() =&gt; navData.navigation.navigate({ routeName: 'Cart' })}
                  /&gt;
              &lt;/HeaderButtons&gt;
          )
      };
  };
  ...styles
  
  </code></pre>