<?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 Ifeoluwa Olorunnegan on Medium]]></title>
        <description><![CDATA[Stories by Ifeoluwa Olorunnegan on Medium]]></description>
        <link>https://medium.com/@ifenega?source=rss-db9b27c91c9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nq0md9pfdDPqSLuY</url>
            <title>Stories by Ifeoluwa Olorunnegan on Medium</title>
            <link>https://medium.com/@ifenega?source=rss-db9b27c91c9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:55:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ifenega/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[Custom Hooks in React]]></title>
            <link>https://medium.com/@ifenega/custom-hooks-in-react-1b6d5da29520?source=rss-db9b27c91c9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b6d5da29520</guid>
            <dc:creator><![CDATA[Ifeoluwa Olorunnegan]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 16:09:18 GMT</pubDate>
            <atom:updated>2024-10-10T16:09:18.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dRkES4ubdBpNn9eN" /><figcaption>Photo by <a href="https://unsplash.com/@chris_j_scott?utm_source=medium&amp;utm_medium=referral">Chris Scott</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the things I often struggle with in React is writing clean code. I frequently get feedback from my boss, “Ife, why did you write it like this?” or “Ife, what is this?” This led him to introduce me to <strong>custom hooks</strong>, and honestly, they’ve helped me a lot in writing cleaner code and creating reusable logic that can be used across multiple components.</p><h3><strong>What are custom hooks?</strong></h3><p>Imagine you’re fetching data from an endpoint and have copied the same code into several components. Now, you need to update the logic or API call, and suddenly, it feels messy and hard to maintain. This is where <strong>custom hooks</strong> come in. A custom hook allows you to share logic (like API calls or dynamic filtering) across multiple components from one place.</p><blockquote><strong>Custom hooks help you extract repetitive logic and make it reusable wherever needed. This keeps your code clean, dry, and easier to maintain.</strong></blockquote><h3>How do you create a custom hook?</h3><p>One thing to know about React hooks is that they always start with use. Whether it’s a built-in hook like useState or useEffect, or a custom hook, the convention is the same: hooks start with &quot;use&quot;. It’s also helpful to name your custom hook based on its purpose, like useFilterTableData for filtering table data or useFetchTableData for fetching it.</p><p>Here’s an example of a custom hook to fetch data:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>const useFetch = (url: string) =&gt; {<br>  const [data, setData] = useState&lt;any&gt;(null);<br>  const [loading, setLoading] = useState&lt;boolean&gt;(true);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await fetch(url);<br>        const result = await response.json();<br>        setData(result);<br>      } catch (err) {<br>        setError(&#39;Error fetching data&#39;);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br><br>    fetchData();<br>  }, [url]);<br><br>  return { data, loading, error };<br>};</pre><p>In the above example, I named the hook useFetch following the convention. Then, I wrote the logic to make an API call and return key details like the fetched data, loading state, and error state. Now, I can reuse this hook wherever I need it.</p><p>For example:</p><pre>const MyComponent = () =&gt; {<br>  const { data, loading, error } = useFetch(&#39;https://api.example.com/data&#39;);<br><br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;{error}&lt;/p&gt;;<br><br>  return &lt;div&gt;{JSON.stringify(data)}&lt;/div&gt;;<br>};</pre><h3>Important Note: Custom Hooks Manage Logic, Not State…</h3><p>A key point to remember is that <strong>custom hooks store stateful logic, not state</strong>. Imagine a custom hook that helps you count apples. The hook is like a friend who helps you keep track of how many apples you’ve counted, but you are responsible for writing that number down in a notebook (your component’s state). The hook just manages the counting process — it doesn’t store the number itself.</p><h3>When to use custom hooks</h3><p>I’ve had situations where I’ve written code and later realized, “<strong><em>This should have been a custom hook</em></strong>!” Here are some questions I now ask myself to decide whether a custom hook is needed:</p><ol><li><strong>Will I use this logic in multiple components? </strong>If the same logic (like fetching data, handling forms, or managing timers) is needed across different components, encapsulating it in a custom hook can save you from repeating code.</li><li><strong>Is the logic complex and cluttering my component? </strong>When your component becomes too difficult to read or maintain due to complex state management or side effects, it’s a good idea to extract that logic into a custom hook. This makes your component cleaner and easier to understand.</li><li><strong>Does this logic involve managing state or side effects? </strong>Custom hooks are especially useful when dealing with useState, useEffect, or other built-in hooks. If you find yourself repeating similar state management or side effect logic, that’s a signal to create a custom hook.</li><li><strong>Can I make this logic reusable for different inputs? </strong>Custom hooks can be designed to accept parameters and return results based on those inputs. If your logic can be generalized and used with different data or configurations, it’s a perfect fit for a custom hook.</li><li><strong>Am I improving readability and maintainability by using a hook? </strong>If extracting logic into a custom hook makes your code more readable and easier to maintain in the long run, then it’s worth creating one. The goal is to simplify your components while still keeping them flexible and functional.</li></ol><h3>Conclusion</h3><p>Custom hooks are a powerful tool for writing cleaner, more maintainable code. They help simplify logic and make it reusable, reducing repetition and simplifying debugging. It’s a best practice to consider using custom hooks where applicable. I know I’ll be using them more often!</p><p>Hope this helps! Please leave a comment or feedback if you have any.</p><p>You can also reach out through <a href="https://x.com/ifenega"><strong><em>twitter</em></strong></a> or <a href="https://www.linkedin.com/in/ifeoluwa-olorunnegan/"><strong><em>linkedin</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b6d5da29520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a WhatsApp Status-Like Horizontal Onboarding Carousel Feature using React Native and…]]></title>
            <link>https://medium.com/@ifenega/how-to-create-a-whatsapp-status-like-horizontal-onboarding-carousel-feature-using-react-native-and-9eb7afea753b?source=rss-db9b27c91c9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eb7afea753b</guid>
            <dc:creator><![CDATA[Ifeoluwa Olorunnegan]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 13:01:59 GMT</pubDate>
            <atom:updated>2024-09-07T18:42:48.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Create a WhatsApp Status-Like Horizontal Onboarding Carousel Feature using React Native and <strong>React Native’s </strong><strong>StyleSheet</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5IIikUQ7I23GNlQ3" /><figcaption>Photo by <a href="https://unsplash.com/@maxwbender?utm_source=medium&amp;utm_medium=referral">Max Bender</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For anyone new to mobile development using React Native, one of the most challenging tasks can be creating an onboarding animation flow that allows users to seamlessly transition between multiple images.</p><blockquote>When I saw the design for a project I was working on and tried different methods that didn’t work, I became frustrated. This led me to ask a <a href="https://github.com/certified84">friend</a>, who suggested using a FlatList, which actually worked.</blockquote><h3>Firstly the main carousel component</h3><p>We want to build a carousel that allows you to slide between components, in this case, images. After that, we’ll add the WhatsApp-like animation and pagination.</p><p>We start by creating a view container that houses the entire component and inside this we add a flatList, in this flatList we can render our screen and pass in the different content for each screen, the flatList handles rendering the slides, manages user scroll events, and interacts seamlessly with other parts of the component (like navigation and animations) to provide a smooth and interactive onboarding experience.</p><pre>//The main part of the onboarding components<br><br>  &lt;View style={{ flex: 1, }}&gt;<br><br>       &lt;FlatList<br>             data={slides}<br>             renderItem={renderItem}<br>             horizontal<br>             showsHorizontalScrollIndicator={false}<br>             pagingEnabled<br>             alwaysBounceHorizontal={false}<br>             keyExtractor={(item) =&gt; item.id}<br>             onScroll={Animated.event(<br>                 [{ nativeEvent: { contentOffset: { x: scrollX } } }],<br>                   {<br>                     useNativeDriver: false,<br>                   }<br>             )}<br>             scrollEventThrottle={32}<br>             onViewableItemsChanged={viewableItemsChanged}<br>             viewabilityConfig={viewConfig}<br>             ref={slidesRef}<br>        /&gt;<br><br>   &lt;/View&gt;<br></pre><p>Here are the data and renderItem components.</p><pre>const renderItem = ({ item }: { item: OnboardingSlide }) =&gt; (<br>        &lt;OnboardingItem item={item} /&gt;<br>    );<br>// Dummy data for slides<br>const slides = [<br>    {<br>        id: &#39;1&#39;,<br>        title: &#39;Slide Title 1&#39;,<br>        description: &#39;Description for Slide 1.&#39;,<br>        backgroundImage: { uri: &#39;https://dummyimage.com/600x400/000/fff&#39; },<br>    },<br>    {<br>        id: &#39;2&#39;,<br>        title: &#39;Slide Title 2&#39;,<br>        description: &#39;Description for Slide 2.&#39;,<br>        backgroundImage: { uri: &#39;https://dummyimage.com/600x400/111/eee&#39; },<br>    },<br>    {<br>        id: &#39;3&#39;,<br>        title: &#39;Slide Title 3&#39;,<br>        description: &#39;Description for Slide 3.&#39;,<br>        backgroundImage: { uri: &#39;https://dummyimage.com/600x400/222/ddd&#39; },<br>    },<br>];</pre><p>The scroll event is handled by an event handler that tracks the horizontal scrolling position (contentOffset.x) using Animated.event. This maps the scroll position to the scrollX animated value.</p><pre>onScroll={Animated.event(<br>    [{ nativeEvent: { contentOffset: { x: scrollX } } }],<br>    { useNativeDriver: false }<br>)}</pre><p>and the scrollEventTrottle sets how often the scroll event should be fired. A value of 32 means the event is fired approximately every 32 milliseconds, balancing performance and responsiveness.</p><p>The Animated.event function ties the scroll event to an Animated.Value (scrollX), enabling smooth animations based on the scroll position.</p><p>To track the item (screen) that is being changed or rendered, we pass a callback ( viewableItemsChange )into the onViewableItemsChanged field, this field is called when the viewability of rows changes i.e when the viewable items (items that are currently visible on the screen) change.</p><pre>const viewableItemsChanged = useRef(({ viewableItems }: any) =&gt; {<br>    setCurrentIndex(viewableItems[0].index); // Update the current index based on the first visible item<br>}).current;</pre><p>We use a ref to avoid recreating the function on each render, thereby improving optimization. The setState is used to update the current index based on the first visible item.</p><p>the last two parameters that are used on this component are the viewabilityConfig, which is a configuarble object that determines when an item is considered viewable which in this case is 50%, and the ref, which is a ref to the flatlist that allows us to control the flatlist in some ways e.g to determine when to update the current slide index.</p><pre>const viewConfig = useRef({ viewAreaCoveragePercentThreshold: 50 }).current;<br><br> const slidesRef = useRef(null);</pre><h4><strong>AUTOMATIC SLIDE TRANSITION</strong></h4><p>The next step in this process is automatically controlling the screens to slide in or out after a given amount of time, this was done by passing a timer function into a useEffect.</p><pre>   const progress = useRef(new Animated.Value(0)).current;<br>   const timerRef = useRef&lt;NodeJS.Timeout | null&gt;(null); // Reference to the timer<br><br>   const startTimer = () =&gt; {<br>        // Clear any existing timer<br>        if (timerRef.current) {<br>            clearInterval(timerRef.current);<br>        }<br>        // Reset progress bar animation<br>        progress.setValue(0);<br><br>        // Start the progress animation<br>        Animated.timing(progress, {<br>            toValue: 1,<br>            duration: 10000, // Set duration of 10 seconds per slide<br>            useNativeDriver: false,<br>        }).start();<br><br>        // Start a new timer to move to the next slide after 10 seconds<br>        timerRef.current = setInterval(() =&gt; {<br>            scrollToNextSlide();<br>        }, 10000); // Adjust the time as needed<br>    };<br><br>   // Handle automatic slide transition<br>    useEffect(() =&gt; {<br>        startTimer();<br><br>        // Cleanup the timer on unmount or when index changes<br>        return () =&gt; {<br>            if (timerRef.current) {<br>                clearInterval(timerRef.current);<br>            }<br>            progress.setValue(0);<br>        };<br>    }, [currentIndex]);</pre><p>The startTimer function clears any existing timer and resets settings, starts a new timer to move to the next slide after the set time (in this case 10 seconds), and ensures the timer is cleared and reset whenever the currentIndex changes to prevent multiple timers from running simultaneously. With this the current screen/item that is been rendered is changed automatically based on the set time. The function of the progress bar will be addressed later.</p><h4><strong>To give the carousel a whatsapp status like animation</strong></h4><p>You know that feature on the status page of your social media that allows you to tap to see the next item on your friends status and see how far into the status you are, yes that is what I am talking about.</p><p>Firstly the tap functionality, this is done by just playing around with two pressable elements, styling it to take, in my case 40% of the screen each, giving it a transparent background and giving it a position absolute one to the left and the other on the right. Then I pass the onpress function into it to handle the action of going to the previous or next slide.</p><pre> <br>&lt;Pressable<br>  onPress={handleLeftPress}<br>  style={{<br>    position: &#39;absolute&#39;,<br>    top: 0,<br>    backgroundColor: &#39;transparent&#39;,<br>    height: &#39;100%&#39;,<br>    zIndex: 1,<br>    width: &quot;40%&quot;<br>    left: 0, //for the left side and this will be right: 0 for the opposit side<br>  }} &gt;<br>&lt;/Pressable&gt;<br></pre><p>to handle the action of each pressable element</p><pre>//For the left pressable<br>    const handleLeftPress = () =&gt; {<br>        if (currentIndex &gt; 0) {<br>            slidesRef.current.scrollToIndex({ index: currentIndex - 1 });<br>        }<br>    };<br>//For the right pressable<br>    const handleRightPress = () =&gt; {<br>        if (currentIndex &lt; slides.length - 1) {<br>            slidesRef.current.scrollToIndex({ index: currentIndex + 1 });<br>        } else {<br>            // navigation.navigate(&quot;OnboardingContinueScreen&quot; as never);<br>        }<br>    };</pre><p>The last part is the progress bar, the progress bar visually indicates the time remaining before the carousel automatically transitions to the next slide. It helps to create a smooth and engaging user experience by showing progress for each slide, giving the user an idea of when the next slide will appear. The code for the progress bar can be found in the startTimer function.</p><figure><img alt="An example of the progress bar" src="https://cdn-images-1.medium.com/max/1024/1*FgduarebhPrfxKdpOf5EPw.jpeg" /><figcaption>An example of the progress bar</figcaption></figure><p>For a general overview of what we have discussed so far:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf360f508e4ad389699095de80043f65/href">https://medium.com/media/bf360f508e4ad389699095de80043f65/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*yhYAszdJkOjJGJskP8i7QA.png" /><figcaption>Image of the Carousel</figcaption></figure><p>Hope this helps! Please leave a comment or feedback if you have any.</p><p>You can also reach out through <a href="https://x.com/ifenega"><strong><em>twitter</em></strong></a> or <a href="https://www.linkedin.com/in/ifeoluwa-olorunnegan/"><strong><em>linkedin</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eb7afea753b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>