<?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 Ebelechukwu Doris Okolo on Medium]]></title>
        <description><![CDATA[Stories by Ebelechukwu Doris Okolo on Medium]]></description>
        <link>https://medium.com/@Lady-Dee?source=rss-3f8c5d04701f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RSmAXjlgEJFn5WmFpnavUA.jpeg</url>
            <title>Stories by Ebelechukwu Doris Okolo on Medium</title>
            <link>https://medium.com/@Lady-Dee?source=rss-3f8c5d04701f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:13:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Lady-Dee/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[Managing Side Effects in React with useEffect: A Guide to Component Lifecycle]]></title>
            <link>https://medium.com/@Lady-Dee/managing-side-effects-in-react-with-useeffect-a-guide-to-component-lifecycle-a7b8e963b8d8?source=rss-3f8c5d04701f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7b8e963b8d8</guid>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[useeffect-hook]]></category>
            <category><![CDATA[side-effects]]></category>
            <category><![CDATA[react-component-lifecycle]]></category>
            <category><![CDATA[useeffect-hook-in-react]]></category>
            <dc:creator><![CDATA[Ebelechukwu Doris Okolo]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 09:52:16 GMT</pubDate>
            <atom:updated>2024-11-12T09:52:16.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UsXbftcLgaM0YxOQ" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In React, side effects refer to any interaction between a component and the outside world — actions beyond the typical component logic and rendering process. Handling these side effects is crucial for creating predictable and efficient components, and useEffect is React’s powerful tool for managing them. In this article, we’ll dive into why handling side effects is essential and explore how useEffect provides an effective, lifecycle-aware approach to managing them.</p><h3>Examples of Side Effects in React</h3><ul><li><strong>API Calls</strong>: Fetching data from a server or external resource.</li><li><strong>DOM Manipulation</strong>: Modifying the DOM directly.</li><li><strong>Timers</strong>: Using setTimeout or setInterval to schedule tasks.</li><li><strong>Subscriptions</strong>: Setting up and cleaning up event listeners or other long-running tasks such as WebSocket connections.</li></ul><h3>Why Should Side Effects Be Handled?</h3><p>In React, component render logic should remain free of side effects. Here’s why:</p><ul><li><strong>Purity and Predictability</strong>: Render logic is designed to be pure and predictable, meaning it should produce the same output each time it’s run with the same input. Side effects — like data fetching, subscriptions, or timers — can introduce unpredictable behavior into the render process, disrupting this consistency.</li><li><strong>Efficiency and Performance</strong>: When side effects are included directly in render logic, they can lead to inefficiencies and errors. For example, if a component fetches data without wrapping it in the useEffect hook, it will re-render continuously, causing an infinite loop. This loop occurs because every re-render triggers the data fetch again, which triggers another render, and so on.</li><li><strong>Using useEffect to Manage Side Effects</strong>: React’s useEffect hook is designed to manage these side effects outside of the render cycle. By placing data fetching, subscriptions, or other side effects in useEffect, we ensure that they only occur when intended, such as when the component mounts, updates, or unmounts, depending on the dependencies provided.</li></ul><blockquote>We’ve mentioned “render” and “render cycle” frequently, so let’s add some perspective by discussing the component lifecycle in React. Understanding the component lifecycle will help clarify how the useEffect hook mimics lifecycle stages in functional components and addresses the challenges of managing side effects.</blockquote><h4>How useEffect Hooks Handles Component lifecycle</h4><p>In React, every<a href="https://www.freecodecamp.org/news/react-component-lifecycle-methods/"> component has a lifecycle</a> that includes distinct stages — <em>mounting, updating</em>, and <em>unmounting</em>. Traditionally, these stages were easier to observe in class components, where lifecycle methods controlled behaviors across these phases. With functional components, however, the useEffect hook provides a way to handle these lifecycle-like behaviors effectively, making it possible to manage side effects without disrupting the render cycle.</p><ul><li><strong>The mounting phase</strong>: occurs when a component is created and added to the DOM. This is when the component is initialized and rendered for the first time. This is often where we initiate side effects such as fetching data, setting up subscriptions, or initializing values.To run code only once on mount, we can pass an <em>empty dependency array ([])</em> as the second argument to useEffect, telling React that the effect doesn’t rely on any changing values and should therefore run only after the first render.</li></ul><pre>  useEffect(function() {<br>    async function fetchData() {<br>      const res = await fetch(`http://www.apidata.com`);<br>      const data = await res.json();<br>      setData(data)<br>      console.log(data)<br>    }<br>    fetchData();<br>  },[])</pre><ul><li><strong>The updating phase</strong>: occurs whenever a component’s state or props change, which triggers a re-render to update the component in the DOM. Supposing you are building a user profile page and there is a need to fetch a user details once the user id changes. This will obviously cause a re-render and this re-render is dependent on the user id changing.</li></ul><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function UserProfile() {<br>  const [userData, setUserData] = useState(null); <br><br>  useEffect(() =&gt; {<br>    async function fetchUserData() {<br>      try {<br>       <br>        const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);<br>        const data = await res.json();<br>        setUserData(data); <br>      } catch (error) {<br>        console.error(&#39;Error fetching user data:&#39;, error);<br>      }<br>    }<br><br>    fetchUserData();<br>  }, [userId]); // the dependency array this time is not empty<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;User Profile&lt;/h1&gt;<br>      &lt;div&gt;<br>        {/* Dropdown to change the userId */}<br>        &lt;label&gt;<br>          Select User ID:<br>          &lt;select onChange={(e) =&gt; setUserId(Number(e.target.value))} value={userId}&gt;<br>            &lt;option value={1}&gt;1&lt;/option&gt;<br>            &lt;option value={2}&gt;2&lt;/option&gt;<br>            &lt;option value={3}&gt;3&lt;/option&gt;<br>            &lt;option value={4}&gt;4&lt;/option&gt;<br>          &lt;/select&gt;<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br><br>      {/* Displaying user data */}<br>      &lt;div&gt;<br>        {userData ? (<br>          &lt;div&gt;<br>            &lt;h2&gt;{userData.name}&lt;/h2&gt;<br>            &lt;p&gt;Email: {userData.email}&lt;/p&gt;<br>            &lt;p&gt;Phone: {userData.phone}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ) : (<br>          &lt;p&gt;Loading user data...&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UserProfile;</pre><ul><li><strong>The unmounting phase</strong>: occurs when a component is removed from the DOM, typically to free up resources or memory. useEffect offers a way to clean up side effects by returning a cleanup function from within the effect. This cleanup function is run automatically just before the component unmounts, making it ideal for clearing timers, canceling network requests, or removing event listeners.</li></ul><pre>useEffect(() =&gt; {<br>  const timer = setInterval(() =&gt; {<br>    console.log(&quot;Timer running&quot;);<br>  }, 1000);<br><br>  return () =&gt; clearInterval(timer);<br>}, []);</pre><h4>Conclusion</h4><p>In this article, we explored how React’s useEffect hook manages side effects like data fetching, DOM manipulation, and subscriptions while preserving the component render cycle. We highlighted its role in handling the lifecycle of functional components — specifically during mounting, updating, and unmounting. By using useEffect, side effects can be executed at the right times, ensuring efficient, predictable behavior and reducing unnecessary re-renders.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7b8e963b8d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why and When to Lift State in React: a Practical Guide]]></title>
            <link>https://medium.com/@Lady-Dee/why-and-when-to-lift-state-in-react-a-practical-guide-facfb1d80243?source=rss-3f8c5d04701f------2</link>
            <guid isPermaLink="false">https://medium.com/p/facfb1d80243</guid>
            <category><![CDATA[state-management-in-react]]></category>
            <category><![CDATA[manage-state-in-react]]></category>
            <category><![CDATA[lifting-state-up]]></category>
            <dc:creator><![CDATA[Ebelechukwu Doris Okolo]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 14:43:34 GMT</pubDate>
            <atom:updated>2024-09-13T14:48:45.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="a laptop screen with code and a react logo" src="https://cdn-images-1.medium.com/max/1024/0*XeZY5LfuiBG9ivjB" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>State management in React can often be confusing, but every React developer must master it. In this article, we’ll dive into the concept of lifting state — a crucial technique for managing state across components. While we’ll briefly cover the basics of state in React, the primary focus will be understanding how and when to lift state for better component communication.</p><h3>What is a State?</h3><p>State refers to data that a component needs to retain throughout its lifecycle. It is used to store dynamic information that affects how the user interface (UI) is displayed to the user. For example, the state of a modal can change based on user actions — it could be either open or closed depending on certain conditions. You can think of state as the<em> memory </em>of a component. Whenever a component’s state is updated, React triggers a re-render to reflect the changes in the UI.</p><p>In React, we use the useState hook to declare state variables. For example, the line:</p><pre>const Modal = () =&gt;{<br><br>  //isOpen is the state variable that holds the current value<br>  //setIsOpen is a function we use to change the value of isOpen<br><br>   const [isOpen, setIsOpen] = useState(false);<br>  <br>}<br></pre><h3>Why is State Important?</h3><p>React is <a href="https://www.educative.io/answers/what-is-declarative-programming-in-react"><em>declarative</em></a><em> </em>and for this reason, we do not directly manipulate the Document Object Model(DOM). State updates the view or the UI by re-rendering the component to reflect the new state. Hence making our UI interactive and responsive. It defines component behavior, It allows components to react to user inputs and external data changes. Hence building our application to behave in a <em>reactive way</em>, gave React its name.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const ModalExample = () =&gt; {<br><br>  const [isOpen, setIsOpen] = useState(false);<br><br>  const openModal = () =&gt; {<br>    setIsOpen(true);<br>  };<br><br>  const closeModal = () =&gt; {<br>    setIsOpen(false);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>     <br>      &lt;button<br>        onClick={openModal}<br>        className=&quot;px-4 py-2 bg-blue-500 text-white rounded-md&quot;<br>      &gt;<br>        Open Modal<br>      &lt;/button&gt;<br><br>    <br>      {isOpen &amp;&amp; (<br>        &lt;div className=&quot;fixed inset-0 flex items-center justify-center bg-black bg-opacity-50&quot;&gt;<br>          &lt;div className=&quot;bg-white p-6 rounded-lg shadow-lg&quot;&gt;<br>            &lt;h2 className=&quot;text-xl font-bold mb-4&quot;&gt;Modal Title&lt;/h2&gt;<br>            &lt;p&gt;This is a simple modal example.&lt;/p&gt;<br><br>        <br>            &lt;button<br>              onClick={closeModal}<br>              className=&quot;mt-4 px-4 py-2 bg-red-500 text-white rounded-md&quot;<br>            &gt;<br>              Close Modal<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ModalExample;</pre><h3>Why and When Do We Lift State?</h3><p>Lifting state in React is a common pattern used to share state between components that do not have a direct parent-child relationship. It’s a way we beat the <a href="https://www.geeksforgeeks.org/reactjs-unidirectional-data-flow/"><em>one-way data flow</em></a> principle in React.</p><p>When sibling components have a need to access and modify a piece of state, because they do not have a parent-child relationship the best approach is to lift this state to a closest common ancestor.</p><blockquote>Using a real-life scenario with two siblings, Emma and Johnson, who live separately from their parents but need to attend family events, we can illustrate the concept of state management. If Emma maintains her own calendar and Johnson keeps his, they might face issues such as inconsistencies and duplication of events.</blockquote><blockquote>Now, imagine that there is a central calendar managed by their parents. Emma and Johnson both have access to this central calendar. This approach solves the problems of missing events and duplicating information, thus avoiding inconsistencies. By using a single source of truth (the central calendar), both siblings stay updated and synchronized without having to manage separate calendars.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c63MO_cP2ZkAzSsa" /><figcaption>Photo by <a href="https://unsplash.com/@kevingent?utm_source=medium&amp;utm_medium=referral">Kevin Gent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To illustrate state lifting, let’s look at a practical example: a to-do list app that manages tasks. In this app, a user can input tasks and the estimated time required to complete each task. The tasks and their respective times will then be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*NyI2bLUDEsg-O6T2i7Z3rg.jpeg" /><figcaption>An app that helps you organise your task</figcaption></figure><p>For this example, we need three components:</p><ul><li><strong>App Component (Common Ancestor):</strong> This component will manage the state of the to-do list. It holds the list of tasks and the logic to update this list.</li><li><strong>Form Component:</strong> This component allows the user to input new tasks and their time estimates. It will send this information to the App component.</li><li><strong>ToDo Component:</strong> This component displays the list of tasks and their associated times. It receives this information from the App component.</li></ul><p>Form Component</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const Form = ({ onAdd }) =&gt; {<br>  const [task, setTask] = useState(&#39;&#39;);<br>  const [time, setTime] = useState(&#39;&#39;);<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    if (task &amp;&amp; time) {<br>      onAdd({ task, time });<br>      setTask(&#39;&#39;);<br>      setTime(&#39;&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Enter task&quot;<br>        value={task}<br>        onChange={(e) =&gt; setTask(e.target.value)}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        placeholder=&quot;Time needed&quot;<br>        value={time}<br>        onChange={(e) =&gt; setTime(e.target.value)}<br>      /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Add&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default Form;</pre><p>ToDo Component</p><pre>import React from &#39;react&#39;;<br><br>const ToDo = ({ todos }) =&gt; {<br>  return (<br>    &lt;ul&gt;<br>      {todos.map((todo, index) =&gt; (<br>        &lt;li key={index}&gt;<br>          {todo.task} - {todo.time}<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default ToDo;</pre><p>The App Component</p><pre>import React, { useState } from &#39;react&#39;;<br>import Form from &#39;./Form&#39;;<br>import ToDo from &#39;./ToDo&#39;;<br><br>const App = () =&gt; {<br>  const [todos, setTodos] = useState([]);<br><br>  const handleAdd = (newTodo) =&gt; {<br>    setTodos([...todos, newTodo]);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;To-Do List&lt;/h1&gt;<br>      &lt;Form onAdd={handleAdd} /&gt; <br>      &lt;ToDo todos={todos} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h3>Conclusion</h3><p>Using the example above, we have effectively bypassed the React principle that prohibits sharing state directly between sibling components through props. It is important to emphasize that state lifting was necessary because the Form component is not a parent of the ToDo component, which means we cannot directly pass state as props between these sibling components. Instead, we introduced a common ancestor component, the App component, which manages the state. This approach allows both sibling components to access and interact with the shared state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=facfb1d80243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to middleware functions in Express.js]]></title>
            <link>https://medium.com/@Lady-Dee/introduction-to-middleware-functions-in-express-js-c18903c2485e?source=rss-3f8c5d04701f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c18903c2485e</guid>
            <dc:creator><![CDATA[Ebelechukwu Doris Okolo]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 13:16:45 GMT</pubDate>
            <atom:updated>2023-09-13T13:16:45.687Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article explains in details and summarises middleware functions and how it can be applied</blockquote><p>Middleware is similar to an unseen guardian that ensures that web application or server runs smoothly.Generally in software engineering, middleware is a crucial component that is often in the form of function or component that processes request before they reach the logic of your application.</p><p>Middleware as the name implies positions itself at the middle of<em> request-response cylce</em> inorder to inspect, manipulate, or enhance the request-response as necessary.</p><p>Key players in middleware function : response object,request object and callback function, we would look at these in detail.</p><p><strong>req (request object) :</strong> this is only a conventional naming for the object, it represents the incoming request from the client. information from this request is contained in this object .</p><p><strong>res(response object)</strong> : this is only a conventional naming for the object, it represents the response that will be sent to the client which includes,the header,status codes and response data.</p><p><strong>next(callback function) </strong>: this is a callback function that is named next by convention,but most importantly it enables the midleware stack to pass control to the next middleware function.If a middleware function does not include this next function then the request-response cycle ends there.</p><p>Now ,let’s see a basic example of middleware function in action:</p><p>Assuming you already have Node.js installed on your system and working with Express.js framework,follow these steps:</p><p>Open your project’s terminal and install Express.js with the followining command:</p><pre>npm install express</pre><p>Create a server.js file in your project folder and add the following code:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>  //Middleware function<br>app.use((req, res, next) =&gt; {<br>  console.log(&#39;Logging happens first&#39;);<br>  next(); <br>});<br><br>// Route handler<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello World!&#39;);<br>});</pre><p>Looking at this code snippet above there is an order to which it is written middleware is defined first because once the request comes it goes through the middleware where the necessary logging or processing happens first before the request is passed to the route handler processes the request and sends response to the client.</p><p>An Express application have different kind of middleware:</p><p>Application-level middleware</p><p>Error-handling middleware</p><p><em>Router-level middleware</em></p><p><em>Third-party middleware</em></p><p><em>Custom middleware</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c18903c2485e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>