<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Burak Erdem on Medium]]></title>
        <description><![CDATA[Stories by Burak Erdem on Medium]]></description>
        <link>https://medium.com/@falsemech?source=rss-23abb2ae882b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hR2ZQEJUtl_rGdhMH8HgBA.jpeg</url>
            <title>Stories by Burak Erdem on Medium</title>
            <link>https://medium.com/@falsemech?source=rss-23abb2ae882b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 08:27:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@falsemech/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why I Chose Firestore Over SQL: A Developer’s Journey to NoSQL]]></title>
            <link>https://levelup.gitconnected.com/why-i-chose-firestore-over-sql-a-developers-journey-to-nosql-ce8a4f162833?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8a4f162833</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 18:52:31 GMT</pubDate>
            <atom:updated>2024-09-12T15:11:03.578Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello friends,</p><p>After a year-long hiatus from writing, I finally motivated myself to write again. In this article I’m going to share my thoughts on a topic that has been a significant part of my journey as a developer: the choice between SQL and NoSQL databases. Throughout my career, I’ve found myself at crossroads many times, deliberating whether to stick with the tried-and-true SQL databases or explore the possibilities offered by NoSQL options. The decision was never easy, and like many developers, I wrestled with the pros and cons of each approach.</p><figure><img alt="Choosing database model can be overwhelming" src="https://cdn-images-1.medium.com/max/1024/1*wdfD6ZUgEDBhDGVgBWbXYQ.jpeg" /><figcaption>Image created by Black Labs Flux AI</figcaption></figure><h3>The Struggle: SQL or NoSQL?</h3><p>For years, SQL databases were my go-to choice. Their structure, reliability, and robust support for complex queries made them a safe and familiar option. However, as I began working on more diverse and dynamic projects, I found myself bumping up against the limitations of SQL’s rigid schemas. The need to constantly modify tables, perform migrations, and manage complex joins started to feel like an anchor, slowing down my development process.</p><p>On the other hand, NoSQL databases, with their promise of flexibility and scalability, were intriguing but also came with their own set of challenges. The lack of a fixed schema could lead to potential inconsistencies, and I worried about how well they would scale for larger projects. The decision between SQL and NoSQL became a constant internal debate, one that I often revisited with each new project.</p><p>The turning point came when I was working on a project that required constant changes. SQL databases, while reliable, became a burden as my data needs kept shifting. I was spending too much time managing migrations and trying to fit changing data into rigid tables. That’s when I realized I needed something more flexible — something that could adapt with my application without the constant hassle. This is when I discovered Firestore, offering the scalability and flexibility I was looking for.</p><h3>My Reasons for Choosing Firestore</h3><p>Below I’ve tried to explain the reasons why Firestore has become my go-to database solution:</p><ol><li><strong>Flexibility Over Rigidity</strong><br>Firestore’s NoSQL structure offers flexibility that SQL databases can’t match. Its ability to store data in a more natural, often unstructured way allows me to adjust the data model as projects evolve without worrying about complex migrations or schema changes. For someone used to the rigidity of SQL, this was refreshing.</li><li><strong>Effortless Scalability</strong><br>Scaling SQL databases can be tricky, requiring careful planning and balancing. Firestore, with its global distribution and serverless architecture, scales automatically, letting me focus on building features rather than managing infrastructure.</li><li><strong>Real-time Data as a Standard</strong><br>Firestore makes real-time data updates simple. While adding real-time features to SQL requires extra effort, Firestore has it built-in, making it easy to create apps that respond instantly to user actions for a smooth, interactive experience.</li><li><strong>Simplicity in Handling Offline Data</strong><br>Managing offline data in SQL is often complicated, but Firestore’s built-in offline support automatically syncs data when the connection is restored. This has been crucial for projects with unpredictable connectivity, keeping users productive even offline.</li><li><strong>Integration with the Firebase Ecosystem</strong><br>Firestore integrates seamlessly with Firebase services like authentication, hosting, and cloud functions. This integration allows me to build complete applications without juggling different services, simplifying the development process.</li></ol><h3>Conclusion</h3><p>In the end, I chose Firestore not because it was the easiest option, but because it was the most adaptable to the diverse and evolving nature of my projects. So far, it has proven to be a reliable, scalable, and flexible solution for both small apps and large-scale applications. However, as technology and project needs continue to evolve, my choice of database might change in the future, depending on what new solutions best meet the demands of upcoming projects.</p><p>So what about you? What kind of database do you prefer? Let me know in the comments!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8a4f162833" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/why-i-chose-firestore-over-sql-a-developers-journey-to-nosql-ce8a4f162833">Why I Chose Firestore Over SQL: A Developer’s Journey to NoSQL</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Reanimated 3 Is Out. Let’s Try Shared Transitions!]]></title>
            <link>https://medium.com/better-programming/react-native-reanimated-3-is-out-lets-try-shared-transitions-54710d891c7e?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/54710d891c7e</guid>
            <category><![CDATA[react-native-performance]]></category>
            <category><![CDATA[react-native-reanimated]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[transitions]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 21:55:59 GMT</pubDate>
            <atom:updated>2023-04-12T21:55:59.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to this popular animation technique</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2QaGL8k6Z2OrencM" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa?utm_source=medium&amp;utm_medium=referral">James Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello, there!</p><p>It’s been a while since I last wrote here because I’ve been busy with my new business, which has taken most of my time. Still, I’ve continued reading stories, and last week, an article caught my eye, which was saying React Native Reanimated 3.0 is out. I quickly got excited about it, although I previously had a love/hate relationship with this library. RNR is well known for its complexity in usage and installation but is also praised in the RN world for its performance due to deep native integration.</p><p>Back in RNR 3.0, this version did not significantly change existing APIs but comes with a long-awaited (maybe too long) feature: Shared Transitions!</p><p>For those who are not familiar, Shared Transitions are a popular animation technique where elements are carried over between navigation routes with animations. Although this technique has been achieved with some libraries like react-native-shared-element, it used React native Animated API for a long time, and this caused some performance issues when animating elements. RNR overcomes these side effects with pure native implementation.</p><p>OK! Enough talk. Let’s start with an example. Here, I’m sharing the example snippet directly from the RNR site:</p><pre>import * as React from &#39;react&#39;;<br>import { View, Button } from &#39;react-native&#39;;<br>import { createNativeStackNavigator } from &#39;@react-navigation/native-stack&#39;;<br>import { NavigationContainer } from &#39;@react-navigation/native&#39;;<br>import Animated from &#39;react-native-reanimated&#39;;<br><br>const Stack = createNativeStackNavigator();<br><br>function Screen1({ navigation }) {<br>  return (<br>    &lt;View style={{ flex: 1 }}&gt;<br>      &lt;Animated.View<br>        style={{ width: 150, height: 150, backgroundColor: &#39;green&#39; }}<br>        sharedTransitionTag=&quot;sharedTag&quot;<br>      /&gt;<br>      &lt;Button title=&quot;Screen2&quot; onPress={() =&gt; navigation.navigate(&#39;Screen2&#39;)} /&gt;<br>    &lt;/View&gt;<br>  );<br>}<br><br>function Screen2({ navigation }) {<br>  return (<br>    &lt;View style={{ flex: 1, marginTop: 50 }}&gt;<br>      &lt;Animated.View<br>        style={{ width: 100, height: 100, backgroundColor: &#39;green&#39; }}<br>        sharedTransitionTag=&quot;sharedTag&quot;<br>      /&gt;<br>      &lt;Button title=&quot;Screen1&quot; onPress={() =&gt; navigation.navigate(&#39;Screen1&#39;)} /&gt;<br>    &lt;/View&gt;<br>  );<br>}<br><br>export default function SharedElementExample() {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      &lt;Stack.Navigator screenOptions={{ headerShown: true }}&gt;<br>        &lt;Stack.Screen name=&quot;Screen1&quot; component={Screen1} /&gt;<br>        &lt;Stack.Screen name=&quot;Screen2&quot; component={Screen2} /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>  );<br>}</pre><p>The code is pretty straightforward. We define two different Stack routes and place an Animated.View inside. The only thing to do to share these Animated Views as one is to add sharedTransitionTag prop and tag them with the same value. That’s it! If you run this code, you can see the green box in the screen will be fixed on top of the screen during the page transition and shrunk while animating.</p><p>While the effect is great, most of the time, you don’t want to animate boxes. Shared Transitions are mostly used on list images, e.g., galleries, catalogues, etc. When an item is clicked in a list, you may want to pop out its image and move it over to the item detail screen, for example. So, let’s try this:</p><pre>import {NavigationContainer, useNavigation} from &#39;@react-navigation/native&#39;;<br>import {createNativeStackNavigator} from &#39;@react-navigation/native-stack&#39;;<br>import React from &#39;react&#39;;<br>import {<br>  Dimensions,<br>  FlatList, <br>  Image,<br>  SafeAreaView,<br>  StyleSheet,<br>  TouchableOpacity<br>} from &quot;react-native&quot;;<br>import Animated, {<br>  Easing,<br>  SharedTransition<br>} from &#39;react-native-reanimated&#39;;<br><br>const {width} = Dimensions.get(&#39;window&#39;);<br><br>const SIZE_IMAGE = width / 3;<br><br><br>const dataImages = [<br>  &#39;https://fastly.picsum.photos/id/756/300/300.jpg?hmac=ihyfC35Qzh798wqV3x_k5A3jEaY9lRiC4w1azntXksM&#39;,<br>  &#39;https://fastly.picsum.photos/id/71/300/300.jpg?hmac=lavbXU_aeHIi1agvKBKJYbgbtDFTCCdGDuzngtJVQjE&#39;,<br>  &#39;https://fastly.picsum.photos/id/1012/300/300.jpg?hmac=FpdcKpoTxl0CZdLj7RjrTjISpiu8TtsesR9f4Fm2yOk&#39;,<br>  &#39;https://fastly.picsum.photos/id/794/300/300.jpg?hmac=EOGWbvHbcjble_4y30-aBz6-AcjjWyNAfFlbfmS1r9U&#39;,<br>  &#39;https://fastly.picsum.photos/id/634/300/300.jpg?hmac=Xydl14x40_5ZjRDqaIAqxyQcuSub_xDcabmUtuE-eD8&#39;,<br>  &#39;https://fastly.picsum.photos/id/862/300/300.jpg?hmac=omllSASwYQXWPO584bLQUz6GetRL0GRe-2QctRXVnJA&#39;,<br>  &#39;https://fastly.picsum.photos/id/3/300/300.jpg?hmac=RT2JK6MzdIgNIWoIj61uPcz8aOSOi3lu2vhnwOxs7lY&#39;,<br>  &#39;https://fastly.picsum.photos/id/639/300/300.jpg?hmac=dQz9oW6E7gTcgpjQvsXItRygy6Z5kL2mc5sqN8bTeRw&#39;,<br>  &#39;https://fastly.picsum.photos/id/840/300/300.jpg?hmac=jYWhgnilJlqSvqrNyakWLPa67a5HJcAVGKo5vbXfJWc&#39;,<br>  &#39;https://fastly.picsum.photos/id/994/300/300.jpg?hmac=GDm1Mpq1ylmjwx5Dv9u-l1nNEAKFDBQyanBzp7Nl4yg&#39;,<br>  &#39;https://fastly.picsum.photos/id/242/300/300.jpg?hmac=o4XyRlR53cSyXOhNnSoYw3pNc6AiUawAVed124gdQZs&#39;,<br>  &#39;https://fastly.picsum.photos/id/857/300/300.jpg?hmac=_2o0QaHplHuWOr4ETeEP5_3Wo6lgNhoxZgeb0yjFckc&#39;,<br>  &#39;https://fastly.picsum.photos/id/217/300/300.jpg?hmac=BsPwAcRl68EZm3jQkeJOcTySx7bzPELlYkwkkl-itpc&#39;,<br>  &#39;https://fastly.picsum.photos/id/1041/300/300.jpg?hmac=PosL0KGsFiR_uaOxVY5r9pvWRIyIpn07BSV53jT6We0&#39;,<br>  &#39;https://fastly.picsum.photos/id/858/300/300.jpg?hmac=_ejZ2a4fSroS4BO_gXXIxq7hyd0RIHSP290jgbqMO2c&#39;,<br>];<br><br><br>const GalleryItem = ({url}) =&gt; {<br>  const navigation = useNavigation();<br>  return (<br>    &lt;TouchableOpacity<br>      onPress={() =&gt; {<br>        navigation.navigate(&#39;Detail&#39;, {url});<br>      }}&gt;<br>      &lt;Animated.View<br>        sharedTransitionTag={`container_${url}`}<br>        style={styles.image}&gt;<br>        &lt;Image<br>          resizeMode=&quot;cover&quot;<br>          source={{uri: url}}<br>          style={StyleSheet.absoluteFillObject}<br>        /&gt;<br>      &lt;/Animated.View&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br>};<br><br>const ListImage = () =&gt; {<br>  // func<br>  const renderImage = ({item}) =&gt; {<br>    return &lt;GalleryItem url={item} /&gt;;<br>  };<br><br>  const keyExtractor = (item) =&gt; {<br>    return item;<br>  };<br><br>  // render<br>  return (<br>    &lt;SafeAreaView style={styles.root}&gt;<br>      &lt;FlatList<br>        numColumns={3}<br>        renderItem={renderImage}<br>        keyExtractor={keyExtractor}<br>        data={dataImages}<br>      /&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>};<br><br>const DetailImage = ({<br>  route: {<br>    params: {url},<br>  },<br>}) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;SafeAreaView style={styles.root}&gt;<br>        &lt;Animated.View<br>          sharedTransitionTag={`container_${url}`}<br>          style={styles.detailImage}&gt;<br>          &lt;Image<br>            source={{uri: url}}<br>            style={StyleSheet.absoluteFillObject}<br>          /&gt;<br>        &lt;/Animated.View&gt;<br>      &lt;/SafeAreaView&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>const Stack = createNativeStackNavigator();<br><br>const App = () =&gt; {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      &lt;Stack.Navigator&gt;<br>        &lt;Stack.Screen name=&quot;List&quot; component={ListImage} /&gt;<br>        &lt;Stack.Screen name=&quot;Detail&quot; component={DetailImage} /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>  );<br>};<br><br>const styles = StyleSheet.create({<br>  root: {<br>    flex: 1,<br>  },<br>  detailImage: {<br>    width: width,<br>    height: 200,<br>    overflow: &#39;hidden&#39;,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>  },<br>  image: {<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>    width: SIZE_IMAGE,<br>    height: SIZE_IMAGE,<br>    overflow: &#39;hidden&#39;,<br>    borderWidth: 1,<br>    borderColor: &#39;#ffffff&#39;,<br>    borderRadius: 10,<br>  },<br>});<br><br>export default App;</pre><p>Here we have two screens: one is a flatlist of random images, and second, is the detail screen where the image is expanded. The URLs of the images distinguish the shared tags. You will see something wrong if you click an image in the list. The image itself has not animated; rather, the container (View) is. You can overcome this issue by making the image Animated.Image and adding Shared Transition to the image itself too like this:</p><pre>&lt;Animated.View<br>    sharedTransitionTag={`container_${url}`}<br>    style={styles.detailImage}&gt;<br>    &lt;Animated.Image<br>      sharedTransitionTag={`image_${url}`}<br>      resizeMode=&quot;cover&quot;<br>      source={{uri: url}}<br>      style={StyleSheet.absoluteFillObject}<br>     /&gt;<br>&lt;/Animated.View&gt;</pre><p>Now the animation becomes smooth, and there is no jaggy transformation.</p><p>One last thing to do is you can customize the animation. Currently, it supports animating width, height, originX, originY, and transformMatrix. originX and originY may seem strange to you. These are only the reference points of the elements on the screen. To change animation props, you can add sharedTransitionStyle prop to transitioning elements and define a custom-style object as a worklet via SharedTransition.custom method. I’m not a fan of Sine animations, so let’s change it to Quad:</p><pre> <br>const transition = SharedTransition.custom(values =&gt; {<br>  &#39;worklet&#39;;<br>  return {<br>    width: withTiming(values.targetWidth, {<br>      easing: Easing.quad<br>    }),<br>    height: withTiming(values.targetHeight, {<br>      easing: Easing.quad<br>    }),<br>    originX: withTiming(values.targetOriginX, {<br>      easing: Easing.quad<br>    }),<br>    originY: withTiming(values.targetOriginY, {<br>      easing: Easing.quad<br>    }),<br>  };<br>});<br><br>&lt;Animated.View<br>        sharedTransitionTag={`container_${url}`}<br>        sharedTransitionStyle={transition}<br>        style={styles.image}&gt;<br>        &lt;Animated.Image<br>          sharedTransitionTag={`image_${url}`}<br>          sharedTransitionStyle={transition}<br>          resizeMode=&quot;cover&quot;<br>          source={{uri: url}}<br>          style={StyleSheet.absoluteFillObject}<br>        /&gt;<br>  &lt;/Animated.View&gt;</pre><p>And the animation will be much more quick and dynamic.</p><p>So the final file would look like this:</p><pre>import {NavigationContainer, useNavigation} from &#39;@react-navigation/native&#39;;<br>import {createNativeStackNavigator} from &#39;@react-navigation/native-stack&#39;;<br>import React from &#39;react&#39;;<br>import {<br>  Dimensions,<br>  FlatList,<br>  ListRenderItemInfo,<br>  SafeAreaView,<br>  StyleSheet,<br>  TouchableOpacity,<br>} from &#39;react-native&#39;;<br>import Animated, {<br>  Easing,<br>  SharedTransition,<br>  withTiming,<br>} from &#39;react-native-reanimated&#39;;<br><br>const {width} = Dimensions.get(&#39;window&#39;);<br><br>const SIZE_IMAGE = width / 3;<br><br><br>const dataImages = [<br>  &#39;https://fastly.picsum.photos/id/756/300/300.jpg?hmac=ihyfC35Qzh798wqV3x_k5A3jEaY9lRiC4w1azntXksM&#39;,<br>  &#39;https://fastly.picsum.photos/id/71/300/300.jpg?hmac=lavbXU_aeHIi1agvKBKJYbgbtDFTCCdGDuzngtJVQjE&#39;,<br>  &#39;https://fastly.picsum.photos/id/1012/300/300.jpg?hmac=FpdcKpoTxl0CZdLj7RjrTjISpiu8TtsesR9f4Fm2yOk&#39;,<br>  &#39;https://fastly.picsum.photos/id/794/300/300.jpg?hmac=EOGWbvHbcjble_4y30-aBz6-AcjjWyNAfFlbfmS1r9U&#39;,<br>  &#39;https://fastly.picsum.photos/id/634/300/300.jpg?hmac=Xydl14x40_5ZjRDqaIAqxyQcuSub_xDcabmUtuE-eD8&#39;,<br>  &#39;https://fastly.picsum.photos/id/862/300/300.jpg?hmac=omllSASwYQXWPO584bLQUz6GetRL0GRe-2QctRXVnJA&#39;,<br>  &#39;https://fastly.picsum.photos/id/3/300/300.jpg?hmac=RT2JK6MzdIgNIWoIj61uPcz8aOSOi3lu2vhnwOxs7lY&#39;,<br>  &#39;https://fastly.picsum.photos/id/639/300/300.jpg?hmac=dQz9oW6E7gTcgpjQvsXItRygy6Z5kL2mc5sqN8bTeRw&#39;,<br>  &#39;https://fastly.picsum.photos/id/840/300/300.jpg?hmac=jYWhgnilJlqSvqrNyakWLPa67a5HJcAVGKo5vbXfJWc&#39;,<br>  &#39;https://fastly.picsum.photos/id/994/300/300.jpg?hmac=GDm1Mpq1ylmjwx5Dv9u-l1nNEAKFDBQyanBzp7Nl4yg&#39;,<br>  &#39;https://fastly.picsum.photos/id/242/300/300.jpg?hmac=o4XyRlR53cSyXOhNnSoYw3pNc6AiUawAVed124gdQZs&#39;,<br>  &#39;https://fastly.picsum.photos/id/857/300/300.jpg?hmac=_2o0QaHplHuWOr4ETeEP5_3Wo6lgNhoxZgeb0yjFckc&#39;,<br>  &#39;https://fastly.picsum.photos/id/217/300/300.jpg?hmac=BsPwAcRl68EZm3jQkeJOcTySx7bzPELlYkwkkl-itpc&#39;,<br>  &#39;https://fastly.picsum.photos/id/1041/300/300.jpg?hmac=PosL0KGsFiR_uaOxVY5r9pvWRIyIpn07BSV53jT6We0&#39;,<br>  &#39;https://fastly.picsum.photos/id/858/300/300.jpg?hmac=_ejZ2a4fSroS4BO_gXXIxq7hyd0RIHSP290jgbqMO2c&#39;,<br>];<br><br><br>const transition = SharedTransition.custom(values =&gt; {<br>  &#39;worklet&#39;;<br>  return {<br>    width: withTiming(values.targetWidth, {<br>      easing: Easing.quad<br>    }),<br>    height: withTiming(values.targetHeight, {<br>      easing: Easing.quad<br>    }),<br>    originX: withTiming(values.targetOriginX, {<br>      easing: Easing.quad<br>    }),<br>    originY: withTiming(values.targetOriginY, {<br>      easing: Easing.quad<br>    }),<br>  };<br>});<br><br>const GalleryItem = ({url}) =&gt; {<br>  const navigation = useNavigation();<br>  return (<br>    &lt;TouchableOpacity<br>      onPress={() =&gt; {<br>        navigation.navigate(&#39;Detail&#39;, {url});<br>      }}&gt;<br>      &lt;Animated.View<br>        sharedTransitionTag={`container_${url}`}<br>        sharedTransitionStyle={transition}<br>        style={styles.image}&gt;<br>        &lt;Animated.Image<br>          sharedTransitionTag={`image_${url}`}<br>          sharedTransitionStyle={transition}<br>          resizeMode=&quot;cover&quot;<br>          source={{uri: url}}<br>          style={StyleSheet.absoluteFillObject}<br>        /&gt;<br>      &lt;/Animated.View&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br>};<br><br>const ListImage = () =&gt; {<br>  // func<br>  const renderImage = ({item}: ListRenderItemInfo&lt;string&gt;) =&gt; {<br>    return &lt;GalleryItem url={item} /&gt;;<br>  };<br><br>  const keyExtractor = (item: string) =&gt; {<br>    return item;<br>  };<br><br>  // render<br>  return (<br>    &lt;SafeAreaView style={styles.root}&gt;<br>      &lt;FlatList<br>        numColumns={3}<br>        renderItem={renderImage}<br>        keyExtractor={keyExtractor}<br>        data={dataImages}<br>      /&gt;<br>    &lt;/SafeAreaView&gt;<br>  );<br>};<br><br>const DetailImage = ({<br>  route: {<br>    params: {url},<br>  },<br>}) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;SafeAreaView style={styles.root}&gt;<br>        &lt;Animated.View<br>          sharedTransitionTag={`container_${url}`}<br>          sharedTransitionStyle={transition}<br>          style={styles.detailImage}&gt;<br>          &lt;Animated.Image<br>            sharedTransitionTag={`image_${url}`}<br>            sharedTransitionStyle={transition}<br>            resizeMode=&quot;cover&quot;<br>            source={{uri: url}}<br>            style={StyleSheet.absoluteFillObject}<br>          /&gt;<br>        &lt;/Animated.View&gt;<br>      &lt;/SafeAreaView&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>const Stack = createNativeStackNavigator();<br><br>const App = () =&gt; {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      &lt;Stack.Navigator&gt;<br>        &lt;Stack.Screen name=&quot;List&quot; component={ListImage} /&gt;<br>        &lt;Stack.Screen name=&quot;Detail&quot; component={DetailImage} /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/NavigationContainer&gt;<br>  );<br>};<br><br>const styles = StyleSheet.create({<br>  root: {<br>    flex: 1,<br>  },<br>  detailImage: {<br>    width: width,<br>    height: 200,<br>    overflow: &#39;hidden&#39;,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>  },<br>  image: {<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>    width: SIZE_IMAGE,<br>    height: SIZE_IMAGE,<br>    overflow: &#39;hidden&#39;,<br>    borderWidth: 1,<br>    borderColor: &#39;#ffffff&#39;,<br>    borderRadius: 10,<br>  },<br>});<br><br>export default App;</pre><p>You can, of course, experiment with different easing functions, maybe add some delays, and make it much cooler!</p><h3>Conclusion</h3><p>React Native Reanimated takes an important part in a React Native application to make it look native with 60fps animations. After Layout Transitions was introduced in version 2.0, this library kept improving and becoming more user-friendly.</p><p>Before ending this article, I should also mention that this feature is designed to use only with react-navigation, so there is no react-native-navigation implementation (who uses it anyway?), and also it’s in beta. So be careful when you move into production and ensure it runs smoothly on all platforms.</p><p>Thanks for reading.</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54710d891c7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/react-native-reanimated-3-is-out-lets-try-shared-transitions-54710d891c7e">React Native Reanimated 3 Is Out. Let’s Try Shared Transitions!</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create an Avengers Snap Effect With Canvas and React]]></title>
            <link>https://medium.com/better-programming/avengers-snap-effect-with-canvas-and-react-ab698de17bc?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab698de17bc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 22:17:55 GMT</pubDate>
            <atom:updated>2022-12-03T14:08:34.238Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s make another Marvel character disappear!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*P-wQVmiEFdrgWnou" /><figcaption><a href="https://www.marvel.com/movies/avengers-infinity-war">Image from Avengers: Infinity War</a></figcaption></figure><p>Recently I binge-watched the Avengers movies on Disney+ (again!), and when I saw Thanos snap his fingers and turn nearly everyone into dust, I reminisced about an old animation I made years ago with Adobe Flash. It was a dissolving effect of an image that has uncanny resemblances with the film.</p><p>This article will teach us how to make particles out of image pixels and animate them individually.</p><p>So, this is the effect we’re going to make:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5ZWr7wPvPDw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5ZWr7wPvPDw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5ZWr7wPvPDw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/024ea6a1ceb5c26ce92d748e550f53c8/href">https://medium.com/media/024ea6a1ceb5c26ce92d748e550f53c8/href</a></iframe><p>Cool, let’s start!</p><blockquote><strong>A quick note: </strong>Even though the title says React, the animation code is written in bare JavaScript, so you can easily change React parts with document.querySelector or equivalent.</blockquote><h3>Preparing our Canvas</h3><p>Our victim for this project, as you saw in the video, will be Wanda Maximoff, aka Scarlett Witch. Of course, you can choose any MCU character you want. Just be mindful that the image should have a transparent background and not be too big for performance reasons. Something like 600x400 should be fine.</p><p>Let’s start by adding a canvas and loading our image in it. Here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32309629cf82254524c19cad981de6de/href">https://medium.com/media/32309629cf82254524c19cad981de6de/href</a></iframe><p>The code here is pretty straightforward. First, we create ref for our canvas, then in our useEffect we check if our canvas is loaded. If so, we access the context and set our canvas width and height to the window’s inner sizes. This makes our canvas take the whole screen (canvas size should be defined in units, CSS units alone would not be sufficient).</p><p>The styles are all 100% in width and height, so we’ll be working in the full viewport.</p><p>Then we load our image with the Image element and draw it into our canvas via context’s drawImage method. The second and third arguments are the position of the image, so with a simple calculation, we can place our image in the center of our page.</p><p>So far, nothing fancy. We’re just showing our Wanda in the middle of the screen. We will now generate particles and a generator (or, say, controller if you want) for those particles.</p><h3>Particle Classes</h3><p>To create particles, we will write classes that you might be familiar with from OOP languages. This will make our code clean and allow us to make changes more easily.</p><p>First, we start with a Particle class like this. You can put this code outside of React function anywhere you want.</p><pre>class Particle {<br>  constructor(x, y, color) {<br>    this.color = color;<br>    this.x = x;<br>    this.y = y;<br>    this.size = 5;<br>   }<br><br>  draw(context) {<br>    context.fillStyle = this.color;<br>    context.fillRect(this.x, this.y, this.size, this.size);<br>  }<br>  update() {<br>    <br>  }<br>}</pre><p>Our particle would be a tiny rectangle in 5px which takes x and y parameters to determine where to put itself in the canvas and which color arguments need to be filled in with which color. The draw method makes our rectangle appear in a specified size and color. Also, we add an update method which we will implement shortly.</p><p>Moving on with our Generator, add this code right after the Particle class:</p><pre>class Generator {<br>  constructor(width, height) {<br>    this.width = width;<br>    this.height = height;<br>    this.particlesArray = [];<br>  }<br><br>  init(context) {<br>    this.particlesArray.push(new Particle(10, 10, &#39;red&#39;));<br>  }<br><br>  draw(context) {<br>    this.particlesArray.forEach((particle) =&gt; particle.draw(context));<br>  }<br><br>  update() {<br>    this.particlesArray.forEach((particle) =&gt; particle.update());<br>  }<br>}</pre><p>The generator class is also pretty straightforward. It behaves like a controller and a container that has the same methods as the Particle class, which allows us to generate, draw and update all particles on the screen. We do this by creating an empty array and pushing every generated particle into it, then looping through it and calling the particle’s own draw and update method. It draws a single red particle, but later we’ll change it into our image pixel.</p><p>Nice! So far, I hope nothing seems unclear because we’ll dive into more challenging things.</p><h3>Getting Pixel Information From the Image</h3><p>As mentioned earlier, we will generate particles according to the pixels of our image and reconstruct the image by those particles. To accomplish that, the Canvas element has getImageData method which returns all pixels&#39; color data of the specified canvas region (More information at: <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData">https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData</a>).</p><p>Now, replace the line where we generate a particle with the line below in Generator’s init method:</p><pre>init(context) {<br>    const pixels = context.getImageData(0, 0, this.width, this.height).data;<br>}</pre><p>If we console.log(pixels) at this point and check the developer tools, we’ll see tons of nested arrays like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*RZpPXnmn-HpiMgGE5Tc9HQ.png" /><figcaption>What da!??</figcaption></figure><p>This is because the getImageData returns raw data in Uint8ClampedArray (clamped here means its value is between 0 and 255) not a formatted one. Now, if you check the values of that array, you’ll notice most of them are 0. But if you pick an array series in the middle of the list, you may see some values like these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*8zPu-QLKMUSJgXQE2CL4pg.png" /><figcaption>Now we’re getting somewhere!</figcaption></figure><p>I think it’s pretty obvious. Those values are the color data of the pixels. The 255 ones are the alpha values, and every three values before them are red, green, and blue, respectively. Since our image sits in the middle of the screen, it’s no surprise we ran into values in the middle rows.</p><p>OK, so how do we handle those arrays? Since they are nested, we need a nested structure to parse them. Modify init like below:</p><pre>init(context) {<br>    const pixels = context.getImageData(0, 0, this.width, this.height).data;<br>     for (let y = 0; y &lt; this.height; y++) {<br>      for (let x = 0; x &lt; this.width; x++) {<br>        const index = (y * this.width + x) * 4;<br>        const red = pixels[index];<br>        const green = pixels[index + 1];<br>        const blue = pixels[index + 2];<br>        const alpha = pixels[index + 3];<br>        const color = `rgb(${red}, ${green}, ${blue})`;<br><br>        if (alpha &gt; 0) {<br>          this.particlesArray.push(new Particle(x, y, color));<br>        }<br>      }<br>    }<br>}</pre><p>Hell of a code! Well, all I can say is that you don’t need to understand it necessarily, but we doing what they call “scanline” in image algorithms. We’re looping through every pixel of our canvas and get an *anchor* for every fourth value. Then we pick the values between them and assign them to RGBA variables consecutively. Finally, we generate a particle for every pixel with an alpha value —meaning not empty.</p><p>When you run the code, you’ll see a copy of our image displayed above our original image, but this time, it’s made of our particles. At the beginning of the animation, we’ll remove the original image so we’ll see only our particles.</p><p>Now, let’s go back to our useEffect and add the following lines:</p><pre>useEffect(() =&gt; {<br>    const canvas = canvasRef.current;<br><br>    if (canvas) {<br>      const ctx = canvas.getContext(&quot;2d&quot;);<br>      ctx.imageSmoothingEnabled = false;<br><br>      canvas.width = window.innerWidth;<br>      canvas.height = window.innerHeight;<br><br>      const generator = new Generator(canvas.width, canvas.height);<br><br>      const image = new Image();<br><br>      image.onload = function () {<br>        ctx.drawImage(<br>          image,<br>          canvas.width / 2 - image.width / 2,<br>          canvas.height / 2 - image.height / 2<br>        );<br><br>        generator.init(ctx);<br>       <br>        startAnimation(<br>          generator,<br>          ctx,<br>          canvas.width,<br>          canvas.height,<br>        );<br>      };<br>      image.src = &quot;/images/wanda.png&quot;;<br>    }<br>  }, []);</pre><p>Here, we initialize our Generator, pass our canvas size and context in init. Also, we define our animation function separately. We would maybe keep it inside useEffect, but we need to make sure that it runs once. So, let’s wrap this part with useCallback and place it above useEffect.</p><pre>const startAnimation = useCallback((generator, ctx, w, h, count) =&gt; {<br>     function animate() {<br>      ctx.clearRect(0, 0, w, h);<br>      generator.draw(ctx);<br>      generator.update();<br>      requestAnimationFrame(animate);<br>    }<br>    setTimeout(() =&gt; animate(), 2000);<br>  }, []);</pre><p>This is where the animation happens. First, we start with setTimeout to give the audience a short time to see the original image so they can catch how the animation starts. Later ouranimate() function runs and first clears our canvas (our original image disappears that way), then calls Generator’s draw and update method, which essentially calls Particle’s draw and update method to draw the entire canvas with updated particles. And with window.requestAnimationFrame or simply, requestAnimationFrame we rinse and repeat the process.</p><p>OK, so before running our code, we need to update our Particle class otherwise nothing will happen:</p><pre>lass Particle {<br>  constructor(x, y, color) {<br>    this.color = color;<br>    this.x = x;<br>    this.y = y;<br>    this.size = 5;<br>    this.vx = -Math.random() * 2;<br>    this.vy = -Math.random() * 2;<br>    this.vFactor = 1.01;<br>  }<br><br>  draw(context) {<br>    context.fillStyle = this.color;<br>    context.fillRect(this.x, this.y, this.size, this.size);<br>  }<br>  update() {<br>    this.x += this.vx;<br>    this.y += this.vy;<br>    this.vx *= this.vFactor;<br>    this.vy *= this.vFactor;<br>  }<br>}</pre><p>Here, we add velocity values as vx and vy and let them have a random value between 0 and 2. Notice also they are negative values that allow the particle to go up and left of the screen. This would give the effect that some breeze is blowing on the right. I also added a velocity multiplier, vFactor, which makes particles accelerate over time.</p><p>OK, let’s have a look at what we have so far:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f356616ed78ad4f2538edaa4b7ac32af/href">https://medium.com/media/f356616ed78ad4f2538edaa4b7ac32af/href</a></iframe><p>Good! Now, if we run the code, we see the image of Wanda briefly, then it will burst completely into particles rather than dissolving. This is not exactly what we want, and it’s sluggish too.</p><p>That happens because we add more particles than we need. The particle size is 5, but we generate particles for every pixel. To fix that, introduce a gap variable where it allows us to generate fewer particles like this:</p><pre>class Generator {<br>  constructor(width, height) {<br>    this.width = width;<br>    this.height = height;<br>    this.particlesArray = [];<br>    this.gap = 5;<br>  }<br><br>  init(context) {<br>    const pixels = context.getImageData(0, 0, this.width, this.height).data;<br>    for (let y = 0; y &lt; this.height; y += this.gap) {<br>      for (let x = 0; x &lt; this.width; x += this.gap) {<br>        const index = (y * this.width + x) * 4;<br>        const red = pixels[index];<br>        const green = pixels[index + 1];<br>        const blue = pixels[index + 2];<br>        const alpha = pixels[index + 3];<br>        const color = `rgb(${red}, ${green}, ${blue})`;<br><br>        if (alpha &gt; 0) {<br>          this.particlesArray.push(new Particle(x, y, color));<br>        }<br>      }<br>    }<br><br>   ...<br>}</pre><p>The gap value is equal to pixel size. This way, we can get color values of every fifth pixel of the image, not more, and generate the particle accordingly.</p><p>If you run it now, you see the animation has been fixed, but it is still wrong. We would rather see a disintegrating effect that starts from the head and ends on the toes, just like in the movie. Let’s move on to the next chapter and do it so.</p><h3>Improvements</h3><p>OK, so what’s the way to start the animation from the top and end it at the bottom? We should tell the pixels on top to animate immediately, and others wait for their line. The way to delay things in JavaScript is to wrap them up with setTimeout function, which would be very risky to use here. That’s because we simply have requestAnimationFrame, which runs on milliseconds. So, why don’t we use this function? Let’s modify some parts:</p><p>First let’s get the length of particles in Generator:</p><pre>init(context) {<br>    const pixels = context.getImageData(0, 0, this.width, this.height).data;<br>    for (let y = 0; y &lt; this.height; y += this.gap) {<br>      for (let x = 0; x &lt; this.width; x += this.gap) {<br>       ....<br>      }<br>    }<br><br>    return this.particlesArray.length;<br>}</pre><p>Then get this total and pass it to the startAnimation on useEffect.</p><pre>...  <br>const particlesCount = generator.init(ctx);<br>   startAnimation(<br>      generator,<br>      ctx,<br>      canvas.width,<br>      canvas.height,<br>      particlesCount<br>   );<br>...<br></pre><p>Now, add a counter variable to our startAnimation function. Since we know how many particles there are, we can stop counting when we reach the total particle length.</p><pre>const startAnimation = useCallback((generator, ctx, w, h, count) =&gt; {<br>    let d = 0;<br>    function animate() {<br>      ctx.clearRect(0, 0, w, h);<br>      generator.draw(ctx);<br>      generator.update(d);<br>      if (d &lt;= count) d++;<br>      requestAnimationFrame(animate);<br>    }<br>    setTimeout(() =&gt; animate(), 2000);<br>  }, []);</pre><p>Finally, edit the Generator’s update function based on the counter value like this:</p><pre>update(counter) {<br>    this.particlesArray.forEach((particle, index) =&gt; {<br>      if (index &lt; counter) particle.update();<br>    });<br>  }</pre><p>In this code, we’re saying, “If the position of the particle is lower than the counter value, do nothing because it’s not this particle’s turn yet. Otherwise, start updating, and as long as the counter value exceeds the position, keep updating.”</p><p>OK, if we run code at this point, we can see the animation goes from top to bottom the way we want. Still, the pixels begin animating in exact order, and it feels unnatural. The whole effect looks kind of unraveling fabric.</p><p>Now, let’s fix that and add some randomness to our code. We begin first by modifying the order of pixels. My solution is to duplicate particlesArray and split them into some little arrays containing 50 elements or so, shuffle them individually and flatten them into a single array. There are super useful functions in lodash library for this kind of operation, so let’s install it:</p><pre>npm install lodash --save</pre><p>Then add those lines on the bottom of the Generator’s init function.</p><pre>import {chunk, shuffle} from &#39;lodash&#39;;<br><br>...<br><br>init(context) {<br>    ...<br><br>    let chunks = chunk(this.particlesArray, 50);<br>    this.particlesArray = [];<br>    chunks.forEach((chunk) =&gt; {<br>      this.particlesArray.push(...shuffle(chunk));<br>    });<br><br>    return this.particlesArray.length;<br><br> <br>  }<br> <br></pre><p>We don’t want the whole array to be shuffled because we don’t want the pixels on the bottom would also animate at first. So this way, we keep randomness and order at the same time.</p><p>Last but not least, you may want to speed up particles toward the end. This way, our animation may seem more realistic. Change the counter value in startAnimation to increase more than one over time.</p><pre>const startAnimation = useCallback((generator, ctx, w, h, count) =&gt; {<br>    let d = 0;<br>    function animate() {<br>     ...<br>      if (d &lt;= count) d += 1 + d /100;<br>      requestAnimationFrame(animate);<br>    }<br>    ...<br>  }, []);</pre><p>You can experiment with the speed here with different values other than 100.</p><p>And this is it! The final code would look like this. I also added a button to reload the page and rerun the effect easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a3c4d4751a66d8a61b135005538e09a/href">https://medium.com/media/9a3c4d4751a66d8a61b135005538e09a/href</a></iframe><h3>Conclusion</h3><p>Working with canvas and animations is pure fun. Here we learned how to make a dissolving effect by getting image data on a pixel basis. Once you reconstruct the image with your own particles, you can experiment with different effects by adding some simple algorithms and values.</p><p>And don’t feel bad about Wanda. MCU always resurrects characters!</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab698de17bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/avengers-snap-effect-with-canvas-and-react-ab698de17bc">Create an Avengers Snap Effect With Canvas and React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want To Set Up Your Next React Native Project Faster? Use CLI]]></title>
            <link>https://medium.com/better-programming/want-to-setup-your-next-react-native-project-faster-use-cli-4d0b7ee442d9?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0b7ee442d9</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 16:18:48 GMT</pubDate>
            <atom:updated>2022-11-13T13:44:14.699Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build your own CLI using Node.js</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RwzOA7L__cpSKVYH" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When it comes to setting up your project in React Native, like every framework out there, you’ve got two options:</p><ol><li>You do a fresh install and add your modules one by one</li><li>You clone a starter template, then start coding</li></ol><p>Often, a starter template would be an ideal choice to get things up quickly because it comes with some ready-to-use screens and functions, but the catch is, since the starter kits are not updated frequently, the modules are usually behind their latest versions, so your entire app would possibly be out of date.</p><p>So what can we do instead? Start a project from scratch seems the way to go, but how can we ease and speed up this process?</p><h3>Enter CLI</h3><p>Wait! What CLI are we talking about? In this article, we will be building our own CLI that we’ll use for upcoming projects. Our CLI will be responsible for installing React Native and the modules that you would use frequently. We will also package our CLI and publish it on npm.</p><p>Cool! Let’s start!</p><p>For this project, we’ll be using <a href="https://www.npmjs.com/package/commander">commander.js</a> since we’re in a Node.js environment. Commander.js is a popular and opinionated tool to make command programs in a fashion that you would use on the terminal. We will also be using <a href="https://www.npmjs.com/package/shelljs">shelljs</a> to run shell commands across every OS environment consistently.</p><p>Let’s first decide what will be in the box. Even though there are many great libraries for React Native, the essential ones are pretty much the same. Here is an example list of modules I would be using:</p><ul><li>React Navigation</li><li>Redux Toolkit</li><li>React Native Reanimated</li><li>React Query</li><li>Axios</li><li>Lottie</li><li>Formik and Yup</li></ul><p>Of course, yours may differ, so feel free to add your own. At this point, we can compose an array of those modules like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/388e090f82983509b4e8db11b30d2c33/href">https://medium.com/media/388e090f82983509b4e8db11b30d2c33/href</a></iframe><p>Then, let’s install commander.js by npm i commander --save and start writing our CLI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40ac2e9777262d0fcc97f04455dd04f3/href">https://medium.com/media/40ac2e9777262d0fcc97f04455dd04f3/href</a></iframe><p>Here is the basic version of our command script, which triggers react-native installation and exits after. Let’s break it down for better understanding:</p><p>First, we put a shebang bash directive on top for our script to access portability amid UNIX systems. This is also required for our script to behave like cli when running. Then we introduce our program and define its name, version, and description. I chose rncli as the name, which means when you use it, you have to type rncli in terminal. Commander.js programs have commands, which have arguments, and which have options. Think of npm when you install a module. For example, when you write the following:</p><pre>npm install react-native --save</pre><p>Here we havenpmis our program, install is our command, react-nativeis our argument, and finally --save is our option. The same goes for this example. We got the install command, and we provide the directory to be installed as an argument.</p><p>The arguments are &lt;required&gt; or [optional]. If you omit a required argument, you will get an error.</p><p>Lastly, in the last line, we provide an action to be triggered, and we run the default react-native install command as we were doing it from the terminal.</p><p>Now, let’s go ahead and install our modules:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ec0b22b2c2e74de024a4b855492a508/href">https://medium.com/media/1ec0b22b2c2e74de024a4b855492a508/href</a></iframe><p>Here we generate a concatenated string of module names and provide it to npm install command. We also give the --typescriptoption for users who prefer to write in TS.</p><p>At this point, we achieved what we wanted: a simple, dull CLI that saves us a couple of minutes. However, you would like to improve it a bit more, right?</p><h3>Getting Fancier</h3><p>To make our CLI more friendly and more “modern,” we can add a wizard mode to guide users through the steps. This wizard explains what this program will do, ask the language preferred, and list the module names along with their latest version numbers.</p><p>We first start off by installing the modules below:</p><pre>npm i figlet axios inquier loading-cli --save</pre><p>In short, Inquier allows us to display select lists and inputs. Figlet generates fancy ASCII text, loading-cli and colors-cli to add a bit of color and spinner to our CLI. We will also get package versions through npm endpoint. Thus, we will use axios (which, for me, seems more convenient), but you can also use simple fetch.</p><p>We can now add the new command “wizard,” provide no argument, and let the program guide us step by step.</p><p>So, our final code would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f194cdacc2cdae345f49c8d12674cb2b/href">https://medium.com/media/f194cdacc2cdae345f49c8d12674cb2b/href</a></iframe><p>Cool! Our program is ready. If we pass a “wizard” argument like rncli wizard first, it will list our modules and their latest versions and ask us if we’d like to continue. If we don’t, it will exit immediately. Then it will ask for the language and directory. After getting that information, it will start installing modules as we previously did in bare CLI.</p><h3>Publishing</h3><p>The final step is publishing. Before sending our package to npm, make sure your package.json has these two entries:</p><pre>&quot;main&quot;: &quot;index.js&quot;,<br>&quot;bin&quot;: {&quot;rncli&quot;: &quot;index.js&quot;},</pre><p>Don’t get confused with the bin name here. The package name would display in npm, not the CLI name. If your name is taken, you can change this name with something else.</p><p>Finally, log in to npm and publish your package:</p><pre>npm login<br>npm publish</pre><p>That’s it! Your CLI is published publicly on npm. You can now quickly test with npx rncli wizard and check if things are working.</p><h3>Conclusion</h3><p>In this article, we briefly entered the CLI world and learned how to build a command program in Node.js. It’s not just limited only to React Native. You can use this example and modify it for any language that uses npm, like Angular, React.js, or bare Node.js. You can improve it further by adding a directory structure or make the terminal fancier by adding colors, etc.</p><p>I hope it will be useful for you. If you have any comments, please let me know!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0b7ee442d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/want-to-setup-your-next-react-native-project-faster-use-cli-4d0b7ee442d9">Want To Set Up Your Next React Native Project Faster? Use CLI</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CodePush: The Right Way]]></title>
            <link>https://levelup.gitconnected.com/codepush-the-right-way-7cf24bccde4f?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf24bccde4f</guid>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[app-store]]></category>
            <category><![CDATA[code-push]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 14:54:51 GMT</pubDate>
            <atom:updated>2022-10-06T14:54:51.239Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is not about installing CodePush or how to use it. You can always refer the documentation at: <a href="https://learn.microsoft.com/en-us/appcenter/distribution/codepush/rn-overview">https://learn.microsoft.com/en-us/appcenter/distribution/codepush/rn-overview</a></blockquote><p>When it comes to picking a mobile cross platform for your next project today, you probably will be narrowed down to either choose React Native or Flutter. I usually have a foot on both camps and try to not to stick to only one, but I must say I have got more sympathy for React Native. And one of the main reason of that is, which I believe it’s the same for many others: <strong>CodePush!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ouoT5q54v9rTLDlK" /><figcaption>Photo by <a href="https://unsplash.com/@robman?utm_source=medium&amp;utm_medium=referral">Rob Hampson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For those who don’t know, <strong>CodePush</strong> allows you to send Hot Updates (or Over The Air Updates, if you prefer) which don’t necessarily need to be reviewed by the App Store or Google Play Store. This is especially useful if you’re working on a project that requires lot of changes in a short time, such as e-commerce apps. You just fix or introduce a new function in your app business then send the update and that’s it. Your users receive it immediately, just as if were a website.</p><p>According to the documentation, after installing the library, you just wrap your entry component, which is usually App.js, and you’re good to go. Even it’s sufficient to make it work, you may want to change the way how your users get the updates in order to make your app more user friendly.</p><p>But why do we need to change it? Well, actually you don’t have to. If you do the basic installation, people would get updates on next restart and if it’s an urgent update you can always mark it as “immediate” on App Center’s dashboard and users get it, well, immediately.</p><p>This instant update however, leads your users to misinterpret your app behaviour since it would restart out of sudden as soon as it gets the update. Through my past projects, users reported back to me this behaviour as a “bug” which isn’t but still I realized that it is something bad for UX so I decided to change it.</p><p>First of all, I think users, especially mobile app users, don’t welcome something unexpected. In every interaction or app function, they do expect something familiar that seem meaningful to them. So, first of all, we’re going to add a modal which alerts users that there is an update available so they will be aware what’s going on. CodePush has updateDialog options which you can specify when you wrap component as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c31b2230b58846750caf249db4e01f5c/href">https://medium.com/media/c31b2230b58846750caf249db4e01f5c/href</a></iframe><p>This setting pops up a native alert when update available so your users would know there is an update waiting for them. The title, body and buttons are all in English but <strong>updateDialog </strong>parameter also takes an object where you can customize those. Here’s a full example in German:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/084a16ddf17b2a138247fa40c22c5683/href">https://medium.com/media/084a16ddf17b2a138247fa40c22c5683/href</a></iframe><p>The dialog slightly changes depending on the type of the update. For standart update, you can close the dialog and choose to install it later while the mandatory update leaves you no choice except installing.</p><p>Although we informed users about the update by showing a popup, we also need to show some sort of a progress indicator while downloading it. This ensures that we’re actually getting the update or not. There is no built-in progress in CodePush so we need to make it from scratch.</p><p>CodePush provides several events about the update phases as well the as the bytes transferred during the update as like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db6c2a0b855bd587ba906d275d9e0fbd/href">https://medium.com/media/db6c2a0b855bd587ba906d275d9e0fbd/href</a></iframe><p>Here we have <strong>codePushStatusDidChange</strong> and <strong>codePushStatusDidChange</strong> events which basically allows us to achieve what we want. I know it’s a class component and class functions and your App.js is probably a functional component. You can’t mix those two, but you can always use <strong>codePush.sync </strong>method instead as described here <a href="https://learn.microsoft.com/en-us/appcenter/distribution/codepush/rn-api-ref#codepushsync">https://learn.microsoft.com/en-us/appcenter/distribution/codepush/rn-api-ref#codepushsync</a>. Please note that some users experienced that statuses provided this way may not work as expected.</p><p>Now for the sake of clarity, let’s stick to the class functions and let’s create a separate component only for CodePush. I also want a tiny line progress bar pops up at the bottom of the app, and when downloaded it will read “Downloaded, restarting…” and restarts the app with the update applied. To accomplish this, we have to manually manage the process. Let’s have a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/405ca88d8f4c89a37645e4276b9a8631/href">https://medium.com/media/405ca88d8f4c89a37645e4276b9a8631/href</a></iframe><p>That’s lot of code. Let’s break it down;</p><p>First we define 2 variables, <strong>stat</strong> and <strong>downloadProgress. </strong>The <strong>stat </strong>variable basically is responsible for every layout changes in our component, including turn on/off our modal. The <strong>downloadProgress </strong>on the other hand, is necessary for our progress bar. You can display a percentage if you’d like but in my opinion it’s unnecessary if you have a visual representation somehow.</p><p>Then we have a basic layout. We have a modal and a wrapper view which I applied Layout Animation from react-native-reanimated for making a shrinking effect for the upcoming text inside.</p><p>We’re using 2 of CodePush events, Downloading and Installed, the rest are there just for logging. We also want to restart the app manually, so in CodePush options I changed installModes to be next app restart. One important thing you may have noticed, we need to wrap this component with codePush instead of App.js, thus you have to unwrap your App if you’ve done it previously.</p><p>One more thing; CodePush works in development environment as well. and this may not be something you want. If you want to avoid getting updates while working on a simulator or something, you can edit the bottom part as below:</p><pre>export default codePush({<br>checkFrequency: __DEV__ ? codePush.CheckFrequency.MANUAL : codePush.CheckFrequency.ON_APP_RESUME,<br>installMode: codePush.InstallMode.ON_NEXT_RESTART,<br>mandatoryInstallMode: codePush.InstallMode.ON_NEXT_RESTART,<br>updateDialog: true,</pre><pre>})(CodePushManager);</pre><p>Lastly, we need to put the component in App.js, preferably outside of every Provider components like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf9b77c41a4d379d060002bd498983aa/href">https://medium.com/media/bf9b77c41a4d379d060002bd498983aa/href</a></iframe><p>And that’s it! We have a nice preloader for CodePush updates. You can always experiment with different settings and change different update and installation modes to be best suitable for your project.</p><p>CodePush provides the fastest way to update the content of your app, as well as fixing the bugs immediately. There are some other related topics you may want to check out like versioning. This is something important and I’m planning to mention about it in my upcoming article. Until then;</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf24bccde4f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/codepush-the-right-way-7cf24bccde4f">CodePush: The Right Way</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet FlashList: A better alternative to FlatList for React Native]]></title>
            <link>https://medium.com/better-programming/meet-flashlist-a-better-alternative-to-flatlist-for-react-native-47ed7484718?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/47ed7484718</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 20:31:31 GMT</pubDate>
            <atom:updated>2022-09-15T20:31:31.096Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief guide to the advantages of switching</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*742pGmystg6Pi5Ve" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever since I started to develop with React Native, pretty sure like everyone else, I ran into this warning at least a dozen times:</p><blockquote>VirtualizedList: You have a large list that is slow to update — make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, etc. {“dt”:13861,“prevDt”:1498372326027,“contentLength”:6624}</blockquote><p>Seems familiar, right? This usually happens when we fill up a FlatList with many items which are not just a static image or text but rather with components that have some animations or other interactions in them.</p><p>The FlatList here simply says it can’t handle the list to render smoothly. You can always ignore it as a warning, but it doesn’t mean it will go away. I wish we could live in a world like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RglPAfnli50hY3ey" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before jumping to solutions, let’s dig into this message and find out what those numbers are:</p><p>FlatList, which is based on ScrollView, uses a listing interface called VirtualizedList. Under the hood, VirtualizedList utilizes a rendering API responsible for displaying an enumerable list of items in the form of scroll. Maybe we don’t notice it because we have the latest iPhone, and we do it through Instagram posts all day smoothly. The scrolling action is a huge process-intensive task for a mobile application because not only does it require pre-rendering for the next upcoming content from the top or down, but it also has to display this content with a sliding effect when it’s in the viewport.</p><p>These intensive calculations are called “batches,” and any batch size over the previous one is called “delta.” So the numbers are dt(delta), prevDt(previous delta) and expressed in timestamps, meaning the time passed between batches. The last number is contentLength, which is the whole content size in React Native’s unitless(!) unit. Whenever any delta value passes 500ms and contentLength exceeds five times the viewport size, this error gets triggered. That’s the limit for VirtualizedList to work properly.</p><p>So what can you do about it? You can search the internet or take the reference of FlatList in React Native’s official website and come up with some techniques that optimize the rendering process. Those include using initialNumToRender or removeClippedSubviews props, maybe memoizing the item component or making it pure. Most of the time, whatever you use will make this message go away, and you’ll be just fine.</p><p>But…</p><p>Even if it seems OK, if your project runs on low-end devices, especially the Android ones, you may still get this error. Because it’s simply those techniques that also need to make some calculations to work it out. That being said, what we need to do, is to redirect this burden of processes into some other thread. Maybe, and why not, the UI, right?</p><p>Meet FlashList! A FlatList alternative that runs on UI thread and, as they claim on their website, it runs 10x faster on JS and 5x faster on JS thread. Even considering only half the improvement — these are really great performance boosts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*DMkczGr5C2noU1Vta-u2yA.png" /></figure><p>To use it, you only need to install FlashList using this command:</p><pre>yarn add @shopify/flash-list</pre><p>pod install if you need to replace your existing &lt;FlatList&gt; with &lt;FlashList&gt;. That’s it!</p><p>Yes, FlashList is extremely easy to use because it has the same props as FlatList. That means data, renderItem, ListEmptyScrollComponent, and so on. The only difference is that it uses RecyclerView instead of VirtualizedList as the underlying component, the performance props we mentioned above are unnecessary. Instead, there are other performance and diagnostic props that you can check out at <a href="https://shopify.github.io/flash-list/docs/usage">https://shopify.github.io/flash-list/docs/usage</a>.</p><p>Most notably, estimatedItemSize which you provide your single component’s height. If every item on your list has an equal size, it’ll be super fast because FlashList doesn’t need to recompute items’ sizes individually. If it’s flexible, you can take the sum of your elements’ height and provide it to this prop.</p><p>On the other hand, if you’re targeting low-end devices, you may need additionally tweak the other props, such as getItemType or overrideItemLayout. The “light component” logic still applies in FlashList, so you can check out <a href="https://shopify.github.io/flash-list/docs/fundamentals/performant-components">https://shopify.github.io/flash-list/docs/fundamentals/performant-components</a> to optimize your components.</p><p>I personally didn’t use this library on production so far, but I did some tests on my old Samsung S5 phone, and I can tell the scrolling performance becomes much better when I use FlashList. Previously there were noticeable blank areas while I was scrolling fast, and they were all gone when I switched to it.</p><p>You can go ahead and check the library at <a href="https://shopify.github.io/flash-list/">https://shopify.github.io/flash-list/</a> and easily replace your existing FlatLists with this one. I’m sure you’ll notice the increase in performance, especially if you’re using animations or complex layouts in your items.</p><p><em>Thanks for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47ed7484718" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/meet-flashlist-a-better-alternative-to-flatlist-for-react-native-47ed7484718">Meet FlashList: A better alternative to FlatList for React Native</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zustand: Forget about other state managers]]></title>
            <link>https://falsemech.medium.com/zustand-forget-about-other-state-managers-281f269382a7?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/281f269382a7</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[zustand]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 15:00:24 GMT</pubDate>
            <atom:updated>2022-07-06T15:00:24.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Few months ago, I had to create a website with 3D models for my client, and I obviously thought about using Three.js in my project. I’ve done some 3D sites before, but never with React, instead plain JavaScript. I searched over the net and found the <strong>react-three-fiber </strong>library<strong> </strong>created by a Latin based developer collective <a href="https://pmnd.rs/"><strong>Poimandres</strong></a>. I was happy that finally I had a way to declaratively use Three.js. Anyway, during the installation a dependency caught my eye: <a href="https://github.com/pmndrs/zustand"><strong>Zustand</strong></a>. Maybe the odd name made me curious I don’t know, I decided to look up for it and landed to its GitHub page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ej-1rHTfJ5ji7_5XscrWg.jpeg" /><figcaption>Bear with me</figcaption></figure><p>Thanks God, I’ve ran into this library later I’ve said. Being a super simple manager, Zustand takes the overwhelming process of state management that we’re used to from Redux. In Redux, we’re nearly forced(!) to use structural hierarchy of store, reducers, actions, constants and the fearful immutability techniques, whereas in Zustand none of them exists. There is a store object which is keeping the state and all your necessary functions and variables are defined altogether in this store. That’s it! You don’t define actions or reducers or whatever separately. Let’s have a closer look what it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18fc07d7aca880602718eb6430cf9129/href">https://medium.com/media/18fc07d7aca880602718eb6430cf9129/href</a></iframe><p>As you can clearly see, the store is created with a hook and it contains reducing functions and state variables. You can put this code at the very beginning of our app, preferably in App.js. The <strong>create </strong>function includes a <strong>set </strong>method which allows us to merge the state with the data we want. Zustand is hook oriented, there is no provider context you need to wrap with, which is a big plus considering performance. As your data types increases, you may also want to create hook for each state separately. Say you’re making a blog, you can have useUserStore, usePostsStore, useCommentsStore and so on.</p><p>This is really fantastic in terms of simplicity. You code is short, your methods and states are tidy. You can of course take a look at the documentation for advanced usage but I think most of us needs only that much.</p><p>Now let’s see how we can use it in a component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf2bf846bf7e3a74f375317bb06c4faf/href">https://medium.com/media/bf2bf846bf7e3a74f375317bb06c4faf/href</a></iframe><p>Here we simply call our useStore hook and get the state values as well as the reducer functions. The syntax is identical to useSelector that you’re familiar from React Redux. However there is a tiny difference you might notice; we’re also able to pick the methods from state within this hook. You can also multi-pick state values in a single line as this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4acc6d10713c8ce0d72d679bb4a7cee/href">https://medium.com/media/b4acc6d10713c8ce0d72d679bb4a7cee/href</a></iframe><p>Only thing we need to add here is the <strong>shallow </strong>helper<strong> </strong>function that ensures any of the value of the object change, the state is updated, thus the component re-renders. You can of course write your own equality comparison function for your own needs.</p><p>One of the major advantage of the library is that you don’t actually need <strong>redu-thunk </strong>or any thunk-ish library for <strong>async</strong> operations. I often asked myself why we would need it anyway in first place. You simply define your function async and you’re good to go. Assuming our addTodo function is async, our store would look like.</p><pre>const useStore = create((set) =&gt; ({<br>  todos: [],<br>  addTodo: async (todo) =&gt; {<br>    const response = await axios.post(&#39;path/to/api&#39;, {todo})<br>    set({ todos: [...todos, response.data] })<br>  },<br>}))</pre><p>And that’s it! No more thunk or other middleware.</p><h3>Conclusion</h3><p>Zustand really made my life easier since I’ve discovered it. I hope it would make yours too. It’s really making no sense to use a whole Redux ecosystem just for example keep a single boolean value in the state. Now those days are gone for me :)</p><p>There are couple of other techniques like persisting state, using Immer for immutability but I wanted to keep this article short. You can always check the documentation for those details at: <a href="https://github.com/pmndrs/zustand">https://github.com/pmndrs/zustand</a> . They’re providing great examples to get you on board.</p><p>I also encourage you to follow <a href="https://pmnd.rs/">Poimandres</a>, they are a great community and they did an excellent work with <strong>react-three-fiber </strong>which I intend to cover in my upcoming articles. Until then;</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281f269382a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skia on React Native: First look]]></title>
            <link>https://falsemech.medium.com/skia-on-react-native-first-look-1e32ad4842e8?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e32ad4842e8</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[skia]]></category>
            <category><![CDATA[image-filter]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 17:16:28 GMT</pubDate>
            <atom:updated>2022-06-27T17:16:28.111Z</atom:updated>
            <content:encoded><![CDATA[<p>When Google released Flutter couple of years ago, their motto was simple. They said;</p><blockquote>You have the control of every pixel on screen</blockquote><p>which basically translates into “From now on, you can do anything anywhere in your app including those adorable liquid-like menus or path animation that you could only do in After Effects”. But how they do that?</p><figure><img alt="Skia Logo" src="https://cdn-images-1.medium.com/max/1024/1*7HaXY1akGLVYp0hMSTvpBw.png" /></figure><p>This was actually possible thanks to Skia Library and Rendering Engine that we will cover in this article. For those who don’t know, Skia is a GPU accelerated rendering system that includes many graphical APIs, including path drawing, image filters, custom shaders and a whole set of SVG tools. So guys on Flutter came up with an idea that making a Skia canvas as a whole viewport area of the app and any GUI element inside would be redraw and look like native. Since they are all in Skia canvas, if you would do something fancy, say like “melted” button, you could do it too. This obviously created a wow effect quickly inside the community and since then people created interesting and vibrant designs for their app.</p><p>So we know what Skia is, let’s get back to our topic;</p><p>If you’re a React Native programmer that love to watch tutorials, reading all articles, do all the stuff to improve yourself; chances are you ran into <a href="https://medium.com/u/4bdbd6b3a30a">William Candillon</a>, a brilliant programmer dedicated himself to React Native animations and interactive UIs. In his YouTube channel he has tons of challenging tutorials that make you master on React Native animations or animations in general. When I was watching his videos, I also learnt too much about math concepts and techniques — say trigs for example and how to apply them on common UI interactions. If you’re interested React Native animations in particular, you definitely want to visit his channel at: <a href="https://www.youtube.com/c/wcandillon">https://www.youtube.com/c/wcandillon</a></p><p>Well, around last year William and his friend Christian Falch decided to “port” the Skia Library to React Native and they built a wonderful package called <a href="https://github.com/Shopify/react-native-skia"><strong>react-native-skia</strong></a></p><p>This library brings almost all APIs of Skia Library along with animation techniques that you may be familiar from react-native-reanimated. If you have ever used react-three-fiber for Three JS animation, same concept applies here, every Skia API is performed in a separate context which uses own hooks and values. Let’s start off with an example and later I’ll explain what I mean;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff5650d5178107c015b2d6021e92463/href">https://medium.com/media/6ff5650d5178107c015b2d6021e92463/href</a></iframe><p>This code draws 3 circles with multiply blend mode applied on overlapping parts. So we first define a Canvas for our paint, which basically create a context for our objects. Then we define a Group which allows us to apply transformations, clipping and other operations to its children. Group is essential tag in RN Skia, since the shapes and other objects have no individual transformation properties. So if you’d like to move a Rectangle for example, you have to first wrap it up with Group.</p><blockquote><strong>A quick interruption:</strong><br>React Native Skia has also Imperative API which means instead of declaring tags you simply utilize the library with a set of commands. I don’t cover imperative way in this article as it’s a bit against declarative nature of React. If you find yourself struggling to apply your logic in tags you can switch to Imperative API per component basis. You can find an example here: <a href="https://shopify.github.io/react-native-skia/docs/getting-started/hello-world">https://shopify.github.io/react-native-skia/docs/getting-started/hello-world</a></blockquote><h4>Shapes and Paths</h4><p>Moving on with shapes, React Native Skia has primitive shapes like rectangles, circles, polygons and lines as well as paths defined with SVG notation you’re familiar with. The shapes attributes are almost identical to SVG equivalents like Circle has cx, cy or Rect<strong> </strong>has x, y and so on. The only thing is, there are some elements for specific cases, like <strong>&lt;Box&gt;</strong> element for optimized inner and outer shadows or <strong>&lt;Patch&gt;</strong> element to draw a <a href="https://en.wikipedia.org/wiki/Coons_patch">Coons Patch</a> (I don’t know what’s the use-case of this one).</p><p>The shapes accept a <strong>&lt;Paint&gt;</strong> as their child to modify painting properties such as stroke or fill. Take a look at the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3897afcab72645928db13f09666faa4d/href">https://medium.com/media/3897afcab72645928db13f09666faa4d/href</a></iframe><p>Here we have a Paint tag inside Circle to fill or stroke the circle we’ve drawn. At first this notation may seem you weird, but actually it’s much more convenient to determine relationships with different APIs. The same structure applies to Group as well. In this example Group has an <strong>opacity </strong>prop which affecting everything inside of it. This nested structure with non-visual elements reminded me Flutter widgets like Spacing, Center etc. If you’re coming from Flutter this will seem very familiar to you.</p><h4>Effects and Filters</h4><p>Now the fun part begins: The cool filters! One of the biggest reason you would want to use Skia is absolutely the vast image effects and filters that you can’t normally find in bare React Native framework. Being a rendering engine as well, Skia canvas has a shader model which allows you modify the pixels on the screen whatever the way you want. Remember the beginning of the article?</p><p>So you want a real shadow with cool softness in Android instead of dumb <strong>elevation </strong>prop? No problem! A great menu with background image blurred underneath? Can do that. Pretty much every filter is included as well as the complex ones such as Color Filter or Displacement Map. Additionally there are some generators like Fractal Noise or Turbulent Noise that you can combine with Displacement Map and make your filter much cooler. If none of these are enough you can always write your own shader and make something unique for your taste. The shader language is very similar to GLSL which is used in WebGL and can be playgrounded here: <a href="https://shaders.skia.org/">https://shaders.skia.org/</a></p><p>OK so let’s make a quick demo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2469b8207045ae3c523aa234a289e83c/href">https://medium.com/media/2469b8207045ae3c523aa234a289e83c/href</a></iframe><p>Here we picked up our image and defined a Displacement Map using a Turbulence to generate some sort of Warp Effect. The result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*W6-OZ4fIJd4QG8qo0QASWg.png" /><figcaption>A depressed girl..</figcaption></figure><p>In this example, first thing you notice is the <strong>useImage</strong> hook. React Native Skia has own elements even they are completely similar to base RN Components such as Image. The &lt;Image&gt; tag of Skia takes an Image in form of SkImage type which can be achieved by providing image path to useImage hook. That’s because Skia is performing in UI thread separating from main thread of React Native itself. You’ll see this difference much more when you start messing with animations. After loading our image we can set any filter as a child component of Image tag. You can here combine any filter, play with different values and achieve different results. Of course not to mention, those values are also animatable which we will cover in another article :)</p><h4>Masks</h4><p>For this article, I lastly want to mention about masking features. The masking elements are not some sort of uniform shapes, it’s rather a container that accept any shape or drawing. If you used <strong>react-native-mask </strong>before, it’s just the same style that goes as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/885c3cf0f54e5ac681f50fc023074548/href">https://medium.com/media/885c3cf0f54e5ac681f50fc023074548/href</a></iframe><p>The &lt;Mask&gt; element takes a mask node that could be anything as long as it produces a luminance or alpha value which the element operates on. Here we provide a circle that masking an image which would look like an avatar below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*urP1Gg9rCHJgZNz21NIz6g.png" /><figcaption>Avatar</figcaption></figure><p>You can of course draw shapes, polygons or even use turbulence filters and make the image looks like cloudy.</p><h4>Conclusion</h4><p>Well, those were the main features of React Native Skia that you can enjoy. Obviously there is a huge animation topic I haven’t mentioned here because I’m saving it for another article. There are also couple of trade-offs I’d like point out;</p><ul><li>The library is relatively new and it’s in between alpha and beta stage. That been said, expect some bugs and performance issues.</li><li>In terms of performance, avoid to use it as a FlatList item or something as repetitively generated.</li><li>Custom shaders sometimes doesn’t behave correctly</li><li>When Group element has many children, performance issues rise again. Try to keep it low.</li></ul><p>Despite those and other problems, the library is marvelous and does a wonderful job. The community is also very active and responsive, I’m sure they will fix the bugs quickly on the upcoming versions. I highly suggest to check it out the library now and feel free to express your creativity. Until then;</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e32ad4842e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query: Fetch data magically]]></title>
            <link>https://falsemech.medium.com/react-query-fetch-data-magically-fb4a9192fcbb?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb4a9192fcbb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data-fetching]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 15:27:08 GMT</pubDate>
            <atom:updated>2022-06-13T15:28:33.591Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re in the world of React, or the sister framework React Native, you probably come across of React Query, a library for data fetching conveniently and easily in your project. Having a good reputation on NPM and GitHub, this library grew fast over the years and became an essential tool belt for React developers who are dealing APIs and data fetching in their projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-91gTq9UzA6MVjZAS8slw.png" /><figcaption>JSONs everywhere…</figcaption></figure><p>So whenever you’re deep into API calls and find yourself doing repetitive tasks such as setting states for incoming data, display &amp; dismiss loading indicators, handle errors etc. you can easily use React Query for all this hassle.</p><p>On top of that, the library does the hard work that you likely unwilling to do it: <strong>Caching</strong>! This is especially where React Query shines, giving you flexibility of how and when to cache data. It has also some other powerful features like refetching, interval based fetching, preflight and so on…</p><p>Before we continue with installation, it’s worth to mention at this point that React Query has 2 main concepts as;</p><ul><li><strong>Querying </strong>— Fetching the data</li><li><strong>Mutating </strong>— Creating, updating or deleting the data</li></ul><p>Most of the time, I find myself utilizing query functions/hooks and getting the data instead of setting or deleting. Thus, I will only cover data query as most of the features are meant to do it elegantly.</p><p><strong>OK cool! So how can I use it? <br></strong>First and obvious step is to install library either with <strong>yarn</strong> or <strong>npm. </strong>React-query is pure written in JavaScript so we don’t need to install any native module.</p><pre>yarn add react-query<br>npm install react-query --save</pre><p>Then, we need to wrap up our main component with <strong>QueryClientProvider</strong> to make it available to all descendant components. <strong>QueryClientProvider</strong><em> </em>has clientproperty which takes a <strong>QueryClient</strong> to manage the queries within the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6583472e2c3df50950bb3e27e93b8c1/href">https://medium.com/media/b6583472e2c3df50950bb3e27e93b8c1/href</a></iframe><p>Now we wrapped our app, we can start using library right away. To fetch data simply use <strong>useQuery </strong>hook as below:</p><pre>const [isLoading, data, error] = useQuery(&#39;key&#39;, () =&gt; axios.get(&#39;path/to/api/or/something&#39;))</pre><p>So what’s going on here? Let’s dissect;</p><p>Our <strong>useQuery</strong> hook takes 2 parameters as <strong>key</strong> and <strong>fetching function. </strong>That’s right, React Query doesn’t have built-in fetching mechanism, we need to provide it explicitly. The key on the other hand is necessary for caching. So basically every time we fetch data with the same key React Query will bring it from cache except for the first time. You can quickly realize that you can use this behaviour as an alternative for Redux. If your app relies too much on API data and you occasionally find yourself using this data through the entire app, you can feel free to use React Query this way.</p><p>OK so useQuery returns us bunch of variables. You can get the complete list in <a href="https://react-query.tanstack.com/reference/useQuery">https://react-query.tanstack.com/reference/useQuery</a> but we will use frequently isLoading, data and error. The variables are pretty much self explanatory but here’s a quick explanation</p><ul><li>isLoading: Loading state of the query. You can use this to compose some sort of preloader for your components. So you don’t need a separate state for loading anymore.</li><li>data: The data itself. The data may change actually depending of what you use for fetching. In this example for instance, since we’re using axios we can get the actual data by typing data.data</li><li>error: The case when an error happens you get this object containing a response for the error. Again, in this example for axios you’ll get the actual error data by error.data</li></ul><p>Let’s all see in action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72752a1a890ead5e39f126ba9e7e1d05/href">https://medium.com/media/72752a1a890ead5e39f126ba9e7e1d05/href</a></iframe><p>Here we fetch the data with showing a preloading ahead and if we bump into an error we’re also showing it. The <strong>key</strong> part plays an essential role in this scenario, because React Query caches the response of this request, which means whenever we run it again we will have the same response, hence the same data. If your data is frequently changing, you can also change <strong>staleTime </strong>property to <em>Infinity </em>to make the data would never been stale and get it fresh every time.</p><p>Another feature is that useQuery takes enabledproperty which executes the query only if the specified condition satisfied. This is particularly useful when your query depends to other variables or data. Here’s a quick example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d682eded9bc4fdb9a6bc35e0ee70e5a/href">https://medium.com/media/3d682eded9bc4fdb9a6bc35e0ee70e5a/href</a></iframe><p>You can see here that our cities are dependent to the selected country, thus useQuery that fetching the cities is only triggered when a countryId is set. You can also observe that for multiple useQueries to differentiate hook variables you can use constant aliasing — data: citiesData in this example.</p><h3>Conclusion</h3><p>This article is just made to get you going with React Query to facilitate your API requests and data usage in your website or app. The library includes so much more than I covered here so you can check their beautiful documentation along with examples.</p><p><a href="https://react-query.tanstack.com/overview">Overview</a></p><p>I love this library so much so I will demonstrate more detailed usage of it in my upcoming articles. Until then;</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb4a9192fcbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce Redux boilerplate: Slicers]]></title>
            <link>https://falsemech.medium.com/reduce-redux-boilerplate-slicers-8d30ac811a43?source=rss-23abb2ae882b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d30ac811a43</guid>
            <category><![CDATA[slicer]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Burak Erdem]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 10:20:26 GMT</pubDate>
            <atom:updated>2021-06-03T10:20:26.171Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a while since React comes into scene with enhanced capabilities and features that everyone enjoy. But as the famous quote from the famous movie says: “<strong>With great power comes great responsibility”. </strong>While bringing rich experiences to the users, React also leaves you alone with crucial aspects of such websites or apps. No doubt State Management being the most important one.</p><p>When you started your journey in React, chances high that you’ve heard of Redux, the infamous state management library that everybody complains about being “hard” to learn. While this is partially true, the complexity of the library mainly comes from its theoretical concepts and the divided structure which for a newcomer seems very unfamiliar and bizarre. Given that, you should not just only familiarize yourself with the concepts, also write so much boilerplate code even just for a simple data presentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MOQaoNvFzzN4crrz" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplas</a>h</figcaption></figure><p>Well some time ago, some clever guys noticed the situation and developed a toolkit called <a href="https://redux-toolkit.js.org/"><strong>Redux Toolkit</strong></a><strong>. </strong>Aiming to reduce the burden of the developer, Redux Toolkit comes with a set of tools out of box and simplifies the Redux setup in many ways. This includes configuring the store, automatic thunk injection or other middleware and providing immutability helpers like Immer. One shiny feature of this library is Slicers. These are basically a group of functions replacing actions and reducers at the same time, thus creating a unified bridge for the state. Let’s look into in through an example;</p><p>When you implement bare Redux workflow into your app, you probably end up creating actions, reducers and creators in separate folders as this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*9QapqUzq9mazRbq_XZcTrA.png" /><figcaption>Too many folders and files</figcaption></figure><p>So let’s start converting it to slicers. First we need to install Redux Toolkit</p><pre># Yarn<br>yarn add @reduxjs/toolkit </pre><pre># NPM<br>npm install @reduxjs/toolkit</pre><p>Then create a folder called <strong>redux </strong>and put <strong>store.js </strong>inside of it. For the sake of simplicity, I will use only one reducer which is <strong>users </strong>in my case;</p><pre>import {<br>    combineReducers,<br>    configureStore,<br>    getDefaultMiddleware,<br>} from &#39;@reduxjs/toolkit&#39;;<br><br>import userReducer from &#39;../slicers/users&#39;;<br><br>const <strong><em>store </em></strong>= configureStore({<br>    reducer: combineReducers({users:userReducer}),<br>});<br><br>export default <strong><em>store</em></strong>;</pre><p>What we did here is using <strong>configureStore </strong>we created our store instance and with <strong>combineReducers </strong>we packaged our reducers. Even there is only one reducer, I intentionally used combineReducers to demonstrate the usage of it. Also keep in mind that Redux Toolkit comes with <strong>redux-thunk</strong>, so you don’t need to add it separately. Basically, for the most of the time, that’s all you do for the store.</p><p>Now let’s dive into the fun part and create slicers. Inside <strong>redux</strong> folder make <strong>slicers </strong>folder and inside it create <strong>users.js. </strong>It’s convenient to have separate files for each state instances. As we have only users, we only create a single slicer. Users.js goes like this;</p><pre>import {createSlice} from &#39;@reduxjs/toolkit&#39;<br><br>const initialState = [];<br><br>const userSlice = createSlice({<br>    name: &#39;users&#39;,<br>    initialState,<br>    reducers: {<br>        loadUsers(state, {payload}) {<br>            return payload<br>        },<br>        removeUser(state, {payload}) {<br>            return state.filter(user =&gt; user.id !== payload.id)<br>        },<br>    },<br>})<br><br>export const {<strong><em>loadUsers</em></strong>, <strong><em>removeUser</em></strong>} = docSlice.actions;<br>export default userSlice.reducer;</pre><p>Let’s breakdown what we did here. First we imported <strong>createSlice </strong>function to, well, create our slice. Slices take an initialization object in form of</p><ul><li>name: A name to refer it later when you call from the selectors</li><li>initialState: Starting state, usually empty</li><li>reducers: A group of reducer functions</li></ul><p>The best part here is that you rid of composing reducers and actions separately and you defined all here in a single file. Reducers are now in form of functions and there are no action creators as Redux Toolkit does automatically generates for you.</p><p>Reducers take still state and action parameters and you still need to be careful about immutability concepts. Only thing you do is to export actions and reducer at the same time as in the example.</p><p>Well you might be asking “How do I dispatch them?”. Same concepts you would encounter in plain Redux still apply. If you’re using functional components you will use <strong>useDispatch</strong> hook from <strong>react-redux, </strong>and <strong>connect </strong>for class based components. So for example if we want to remove a user, that would be;</p><pre>import {removeUser} from &#39;../redux/slicers/users&#39;;</pre><pre>const dispatch = useDispatch();</pre><pre>...</pre><pre>dispatch(removeUser({id: 1234}));</pre><p>Notice that we put the payload object directly as we don’t need to create an extra function to pass the state and data. Your editor may complain about the action function should take 2 arguments, and it’s right but our middleware has default thunk function and the state would be passed over without a problem. So you can safely ignore if you’ll have such warning.</p><p>Redux, for those who stepped in React world recently, may have terrifying and exhausting setup and concepts, but you can overcome this by using Redux Toolkit and write the code only for what you need. Not to mention reducing also boilerplate and folder structure, your code would also look clean and understandable.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d30ac811a43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>