title: create Carousel in React Native using FlatList
body: <p>I'm creating a carousel component in React Native using a <code>FlatList</code> and I use <code>useState</code> hook to control the index of image, images load properly and the problem is I cant use my buttons to control the carousel. for example when I tap on right arrow first time doesn't work but when I tap again it goes to next image.
  here's my code:</p>
  <pre class="lang-js prettyprint-override"><code>const { width: windowWidth, height: windowHeight } = Dimensions.get(&quot;window&quot;);
  
  const slideList = Array.from({ length: 5 }).map((_, i) =&gt; {
    return {
      id: i.toString(),
      image: `https://picsum.photos/1440/2842?random=${i}`,
    };
  });
  
  const Carousel = () =&gt; {
    const [current, setCurrent] = useState(0);
    const length = slideList.length;
    const flatListRef = useRef();
  
    const renderItem = ({ item }) =&gt; {
      const arr = Object.values( item );
      return (
        &lt;View style={styles.imagesContainer}&gt;
          &lt;Image style={styles.image} source={{ uri: item.image }} /&gt;
        &lt;/View&gt;
      );
    }
  
    const goNextSlide = () =&gt; {
      setCurrent(current &lt; length -1 ? current + 1 : 0);
      flatListRef.current.scrollToIndex({ index: current, animated: true });
    };
    const goPrevSlide = () =&gt; {
      setCurrent(current &lt;= length - 1 &amp;&amp; current &gt;= 0 ? current -1 : 0);
      flatListRef.current.scrollToIndex({ index: current, animated: true });
    };
  
    console.log(current)
  
    return (
      &lt;View style={styles.screen}&gt;
        &lt;View style={styles.controls}&gt;
          &lt;TouchableOpacity style={styles.controlleft} onPress={goPrevSlide}&gt;
            &lt;CarouselLeftArrow style={styles.leftArrow} size={28} fill='black' /&gt;
          &lt;/TouchableOpacity&gt;
          &lt;TouchableOpacity style={styles.controlRight} onPress={goNextSlide}&gt;
            &lt;CarouselRightArrow style={styles.rightArrow} size={28} fill='black' /&gt;
          &lt;/TouchableOpacity&gt;
        &lt;/View&gt;
        &lt;FlatList
          data={slideList}
          keyExtractor={item =&gt; item.id}
          renderItem={renderItem}
          horizontal={true}
          showsHorizontalScrollIndicator={false}
          pagingEnabled={true}
          ref={flatListRef}
        /&gt;
      &lt;/View&gt;
    )
  }
  
  const styles = StyleSheet.create({
    imagesContainer: {
      width: windowWidth,
      height: 250
    },
    image: {
      width: '100%',
      height: '100%'
    },
    controls: {
      backgroundColor: 'yellow',
      flexDirection: 'row',
      justifyContent: 'space-between',
      position: 'absolute',
      zIndex: 2,
      width: '100%',
      top: 100
    },
    controlLeft: {
  
    },
    controlRight: {
  
    }
  })
  
  export default Carousel;
  
  </code></pre>
  <p>any help would be appreciated.</p>