<?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 Marcelo Botelho on Medium]]></title>
        <description><![CDATA[Stories by Marcelo Botelho on Medium]]></description>
        <link>https://medium.com/@botelhomarcelo7?source=rss-9fd13879ed39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hLhY-0CgSufQo8bRwNIfgQ.png</url>
            <title>Stories by Marcelo Botelho on Medium</title>
            <link>https://medium.com/@botelhomarcelo7?source=rss-9fd13879ed39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:58:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@botelhomarcelo7/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[How to Handle Authentication on React Native (Firebase Example)]]></title>
            <link>https://blog.stackademic.com/how-to-handle-authentication-on-react-native-firebase-example-a5e0132f909d?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5e0132f909d</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 19:12:19 GMT</pubDate>
            <atom:updated>2025-04-07T06:00:03.879Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn the power of useContext in React Native</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBDkwX_3DRkoRN4Xh8Uazg.png" /></figure><p>Today, we’ll explore an effective way to handle authentication and authorization in React Native using the useContext hook.</p><p>This is one of the things that can be confusing for someone new to React Native or React, even for experienced developers. The hierarchical structure of React makes the usual line of thought for implementation services that should be unique inside the scope of the application difficult.</p><p>For those interested in design patterns, this follows the <strong>Singleton Pattern</strong>, a well-known Creational pattern from the <strong>Gang of Four (GoF)</strong>. The key idea is that certain services should have only <strong>one instance</strong> throughout the application to function correctly.</p><p>You can think of this instance through several examples, as the canvas for some drawing application that needs to be accessed by several parts of the code, even in parallel, but can’t be duplicated by any means. The authentication instance fits quite well with that definition too.</p><p>Before diving into our solution, let’s explore a basic approach and see its limitations. Well, we need to respect the following criteria:</p><blockquote>1 — There must be only one “Object” that handles authentication. That means this object needs to pass metadata around and expose functions that can be called.</blockquote><blockquote>2 — This object must be accessible by several parts of the code, and when it changes, those other parts must respond to it.</blockquote><p>To meet these requirements, we could take two common approaches:</p><blockquote><strong>Using global objects: </strong>We create an authentication object and export it globally.</blockquote><blockquote><strong>Lifting state</strong>: We place the authentication logic in a parent component (e.g., Main) and pass it down as props.</blockquote><p>Both solutions may work, but you will have trouble responding to changes (first solution) or passing down information to infinite components on the three (second solution). This is where the useContext hook becomes a game-changer. This hook allows you to create a “Service Provider”, that runs independently, and when called on your App, it enables every component down the line to “subscribe” to its services, removing the need for passing information down, making your code way easier to read and understand.</p><p>Great, we have a solution figured out! Now let’s make it work.</p><h4><strong>Authentication Solution with useContext</strong></h4><p>First, let’s create the Service Provider. Look at the code below:</p><pre>import React, {createContext, useState} from &#39;react&#39;;<br><br>// Creating authentication context<br>const AuthContext = createContext(null)<br><br>//Our Context Provider Component.<br>const AuthContextProvider = (props: any) =&gt; {<br><br>  //Both states that we will be exposing.<br>  const [loading, setLoading] = useState(true) //When the process is loading<br>  const [isAuth, setIsAuth] = useState(false)<br>  <br>  // Login Function<br>  const login = async (email, password) =&gt; {<br>    if (!email || !password) {<br>      console. error(&quot;No email or password&quot;)<br>      return<br>    }<br>  <br>    setLoading(true)<br>    setIsAuth(true)<br><br>    // Check if the password is &quot;12345678&quot;. If true, first send a email reset<br>    if (password === &quot;12345678&quot;) {<br>      setIsAuth(true)<br>      console.log(&quot;Login Successful&quot;)<br>    } else {<br>      console.warn(&quot;Credentials Invalid&quot;)<br>    }<br><br>    setLoading(false)<br>  };<br><br>  // Logout Function<br>  const logout = async () =&gt; {<br>    setLoading(true);<br>    console.log(&quot;Logging Out&quot;)<br>    setIsAuth(false)<br>    setLoading(false);<br>  };<br><br>  // Exposing what we&#39;d like to expose. This can be accessed by any component below.<br>  const variables = {<br>    loading,<br>    isAuth,<br>    login,<br>    logout,<br>  }<br><br>  // Pay attention to this part. It its like putting a header and footer around all the components below this Provider. Now everyone below it can access its information.<br>  return (<br>    &lt;AuthContext.Provider value={variables}&gt;<br>        {props.children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br><br>//Exporting the Context (to access the information), and the Provider (Used by the JSX to instance it)<br>export {AuthContext, AuthContextProvider};</pre><p>This exposes both states (isLoading and isAuth, and the Login and Logout functions). Now that we’ve set up the provider, it will be instantiated once when the app loads. This ensures that authentication data is accessible to &lt;Main /&gt; and all its child components.</p><pre>function App() {<br><br>  return (<br>     &lt;AuthContextProvider&gt;<br>         &lt;Main/&gt;<br>     &lt;/AuthContextProvider&gt;<br>  );<br>}<br><br>export default App;</pre><p>Now that we have a provider, every time the App loads, it will instantiate our provider once and expose its data to the &lt;Main /&gt; component and every other below it. Now, we can implement something as simple as the code below for our Main component:</p><pre>export default function Main() {<br>  //Load auth context provider. This can be accessed by any component below Main.<br>  const {loading, isAuth} = useContext(AuthContext)<br><br>  return (<br>    // If isAuth, then show the Home Screen. If not, then Display the Login page.<br>    !isAuth ? (<br>      &lt;Login /&gt;<br>    ) : (<br>      &lt;Home /&gt;<br>    )<br>  )<br>}</pre><p>And for the &lt;Login /&gt;and &lt;Logout /&gt;components, we can call the Login and Logout functions, to trigger the authentication actions needed. Something like this:</p><pre>const {login, logout }: any = useContext(AuthContext);</pre><p>And that’s it! Now we have an authentication provider that can be adapted to any services in use, such as Auth0, Firebase, Azure, and so on. Also, as this is simple React code, you can use it on React Native, React, NextJS, and any other framework of React. This solution is used by several other popular libraries that you may already use, such as Native Base, Redux, and so forth.</p><p>Just keep in mind that, as with everything in life, this solution has its drawbacks, including:</p><blockquote>1 — For larger apps, solutions with State Management as Redux may be more suitable, as it exposes only what is needed for each part of the app. This is especially important for authentication metadata, which shouldn’t be accessible by all parts of the code.</blockquote><blockquote>2 — Storing this information on states isn’t the safest option. You may adapt your app to use AsyncStorage or SecureStore, for instance.</blockquote><p>Before wrapping up, as promised, you can find a <a href="https://github.com/Medium-Projects/React-Native-Authentication.git"><strong>complete Firebase Authentication implementation</strong></a> in this repository. It includes additional features such as authentication state listeners, password reset, and metadata exposure.</p><p>This includes other needed details, such as a listener for authentication state changes, password reset, and metadata exposure. It may seem much more than the code above, but the idea is the same: it’s a context provider and plays its role in its own space, let’s say.</p><p>Lastly, as I am using Native Base and other needed dependencies, you may also find this repository useful as a skeleton for a new project. I know how painful it is to manage the dependency hell in React Native…</p><p><strong>That’s it! Thanks for reading — happy coding!</strong></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e0132f909d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-handle-authentication-on-react-native-firebase-example-a5e0132f909d">How to Handle Authentication on React Native (Firebase Example)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matter.js with React, and learn to use useRef() effectively.]]></title>
            <link>https://blog.stackademic.com/matter-js-with-react-and-learn-to-use-useref-effectively-8f57365b926e?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f57365b926e</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[matterjs]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 11:55:23 GMT</pubDate>
            <atom:updated>2024-08-12T00:45:56.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HpBCyO68_1vWhKd0vN_1yQ.gif" /><figcaption><strong>Matter.js with React</strong></figcaption></figure><p>Get ready to learn how to use <em>Matter.js</em> in <em>React</em>! 🚀</p><p>Matter.js is a very useful <a href="https://www.geeksforgeeks.org/what-is-vanilla-javascript/"><strong>Vanilla JS</strong></a> library that allows you to do mechanical simulations, animations, and so on. Paired with graphical libraries, like <a href="https://pixijs.download/release/docs/index.html"><strong>PixiJS</strong></a> (I will bring an article on this line soon), it enables you to create astonishing web pages, including games and artistic content.</p><p>As not everything comes easily in life, the first thing you should know is that <a href="https://brm.io/matter-js/docs/"><strong>Matter.js</strong></a> is made for <em>JavaScript</em>, and not specifically for <em>React</em>. What should we do? Can we use it anyway?</p><p>This is the part where we get confused, especially who is starting React, and we end up gravitating towards finding a wrapper library that encapsulates the <em>JavaScript</em> functionalities for us. Not a bad solution, but not a great one either. Usually, these libraries are not as well maintained as the main ones, so they end up having more delay in the updates and may contain potential vulnerabilities or bugs in general.</p><p>The good news is that I will be teaching you today a way to create your wrapper for JS libraries, and using a very special hook from <em>React</em>: useRef</p><p>To begin with, let’s rewind a little and remember how <em>React</em> renders its components:</p><p>As you may know, <em>React</em> only triggers re-renders for the pieces that changed in your application. With that in mind, we can divide the process of rendering a component into two parts: the <strong>“JS block”</strong>, and the <strong>“JSX (HTML-like) block”</strong>. This is a simplified way to think about it — feedback is welcome, but you can look at the difference in the example below:</p><pre>import { useEffect, useRef, useState } from &quot;react&quot;;<br><br>function App() {<br><br>  //JavaScript block<br>  //###########################<br><br>  const [state, setState] = useState(); //My state<br>  const ref = useRef(); //My ref<br><br>  useEffect(() =&gt; {<br>    //useEffect code<br>  },[])<br><br>  // JavaScript object being instantiated<br>  const vanillaJSObject = VanillaJSObject();<br>  <br>  //###########################<br><br>  //JSX (HTML-like) block<br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        MY APP<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default App</pre><p>Remember that <em>React</em> is just a <em>Framework</em> over <em>JavaScript</em>, so when a component gets rendered, <em>React</em> will read the component line by line to check how your variables will behave and how it affects your <em>JSX</em> block. Let’s go through the example above:</p><p>When reading the useState, and useEffect lines, React will execute it during the first render and just skip in the subsequent ones (our useEffect has no state attached), as they are hooks that will considered an element that triggers a re-render.</p><pre>  const vanillaJSObject = VanillaJSObject();</pre><p>Here is the issue. <em>React</em> will instantiate this object repeatedly at every render. So, if this <em>Class</em> is a very complex library and very much stateful, you will be wasting a lot of time recreating it a every render and won’t be able to persist any information inside it. How can we solve this issue? Meet useRefhook.</p><p>The useRef is much more than a hook that lets you access DOM information of your <em>JSX</em> components (If you don’t know what I am talking about, leave a comment and I will teach you how to build a fully functional Carrossel).</p><blockquote>useRef allows us to do a very important job: <strong>tell React rendering process that it should not re-render (in that sense, consider re-instantiate and reconstruct) this specific Component.</strong></blockquote><p>It may seem vague when put with no context, but it perfectly fits our issue: it lets you handle <em>Vanilla JS</em> objects inside our <em>React</em> code. This is the syntax:</p><pre>const myRef = useRef(initialObjectState);</pre><p>Where the initial value can be pretty much anything. In our case, it will be the entire <em>JavaScript</em> object. To get the content, access the current property like this:</p><pre>var Obj = UseRef.current;</pre><p>I am sure you don’t want to hear me talking anymore. Let’s start coding.</p><p>In our project, we are creating a bubble machine (how creative…). The idea is to show how to use the basic components of matter.js in React, blended with mouse and buttons. Just to raise the bar a little bit, we will be adding some color effects to the grains and tweaking some <em>Matter.js</em> Properties for you to know what can be done.</p><p>To simplify the styling and the creation process, we will be using <a href="https://vitejs.dev/guide/"><strong>Vite</strong></a> and <a href="https://tailwindcss.com/docs/guides/vite"><strong>TailwindCSS</strong></a>. Open your <strong>Terminal</strong> and type:</p><blockquote>npm create vite@latest</blockquote><p>Then:</p><p>· Name the <strong>project</strong> and the <strong>package</strong></p><p>· Select <strong>React</strong> and <strong>Typescript</strong></p><p>· <em>cd project_name</em></p><p>·<em> npm install -D tailwindcss postcss autoprefixer</em></p><p>·<em> npx tailwindcss init -p</em></p><p>Add to the <strong>index.css</strong>:</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>Add to the <strong>tailwind.config.js</strong>:</p><pre>  content: [<br>    &quot;./index.html&quot;,<br>    &quot;./src/**/*.{js,ts,jsx,tsx}&quot;,<br>  ],</pre><p>And finally, install <em>matter.js</em>:</p><blockquote><em>npm install matter-js</em></blockquote><p>In our project, let us remove everything from <strong>App.tsx</strong> and start with this:</p><pre>import { useEffect, useRef } from &#39;react&#39;<br>import { Engine, Render, World, Bodies, Runner } from &#39;matter-js&#39;<br><br>function App() {<br><br>  const canvas = useRef&lt;HTMLDivElement&gt;(); //Your div element<br><br>  //Matter.js references<br>  const engine = useRef(Engine.create()); <br>  const render = useRef();<br>  const runner = useRef();<br><br>  //Mouse position. Will be updated at every move.<br>  const posX = useRef&lt;number|null&gt;(null);<br>  const posY = useRef&lt;number|null&gt;(null);<br><br>  //Used to keep the mouse interval trigger.<br>  const mouseIntervalRef = useRef&lt;number|null&gt;(null);<br><br>  //This will only run once. It will initialize the Matter.js render and add the mouse listener.<br>  useEffect(() =&gt; {<br>    initializeRenderer(); //Initialize Matter.js objects<br>    window.addEventListener(&quot;mousemove&quot;, updateMousePosition); //Add mouse listener<br><br>    return () =&gt; { //Done when the component closes. Do the opposite.<br>      clearRenderer(); //Remove all data from Matter.js<br>      window.removeEventListener(&quot;mousemove&quot;, updateMousePosition); //Remove mouse listener.<br>    }<br>  },[])</pre><p>This first block contains all the hooks we will be using. Keep in mind that React won’t restart any of those on subsequent renders. Here we are defining objects for matter.js (engine, render, runner), and for the mouse. Also, notice that we are not using a single useState here.</p><p>This part is the key to understanding our core objective. All those useRef hooks will store their objects in the same manner as the useState hook. The main difference is that they will not trigger renders when they change. This solves our primary issue of not losing the instance at every render and at the same time keeps the code efficient, avoiding unnecessary updates to the <em>UI</em>.</p><p>The useEffect will run once in the beginning, initializing the matter.js components and starting a listener for the mouse position. The return statement will be triggered when the component closes and will be the opposite of the code that came before.</p><p>The next part is the functions for <strong>Matter.js</strong>:</p><pre><br>  //Initialize everything from Matter.js<br>  const initializeRenderer = () =&gt; {<br>    if(!canvas.current) return; //It&#39;s good to always check if your reference exists.<br>    <br>    const height = canvas.current.offsetHeight; //div height<br>    const width = canvas.current.offsetWidth; //div width<br><br>    render.current = Render.create({ //Start renderer, per Matter.js docs.<br>      element: canvas.current, //Our JSX element<br>      engine: engine.current, //The engine<br>      options: {<br>        width: width,<br>        height: height,<br>        wireframes: false, //Just for testing. Remove all colors and details.<br>        background: &#39;#BBBBBB&#39;//Background color<br>      }<br>    });<br><br>    // Adding the objects to the engine. <br>    World.add(engine.current.world, [<br>      Bodies.rectangle(width / 2, height + 10, width, 20, { isStatic: true, friction: 10 }), //Floor<br>      Bodies.rectangle(width+10, height/2, 20, height, { isStatic: true, friction: 10 }), //Right wall<br>      Bodies.rectangle(-10, height/2, 20, height, { isStatic: true, friction: 10 }), //Left wall<br>    ])<br><br>    // Start the engine, the renderer, and the runner. As defined in Matter.js documentation<br>    Engine.run(engine.current);<br>    Render.run(render.current);<br>    runner.current = Runner.create();<br>    Runner.run(runner.current, engine.current);<br>  }<br><br>  //Used to add grains to the renderer. Is the same thing we did when<br>  //added the rigid objects to the scene before.<br>  const addGrain = () =&gt; {<br>    World.add(engine.current.world, [<br>      Bodies.circle(posX.current, posY.current, 8, { //Add a grain to the current mouse position.<br>        friction: 10, restitution: 0.01, density: 0.001,<br>        render: { //Just color change<br>          fillStyle: &#39;#888888&#39;, strokeStyle: &#39;#333333&#39;, lineWidth: 3<br>        }}),<br>    ]);<br>  }<br><br>  //Remove everything when closed. Self-explanatory.<br>  const clearRenderer = () =&gt; {<br>    if(!render.current) return;<br>    Render.stop(render.current);<br>    Runner.stop(runner.current);<br>    render.current.canvas.remove();<br><br>    if(!engine.current) return;<br>    World.clear(engine.current.world);<br>    Engine.clear(engine.current);<br>  }</pre><p>This is the most complicated part of our code. It contains first the function that initializes the renderer and adds the floor and side walls. The second function adds a new grain (a circle) to the canvas and will be called in a loop every time the mouse is held for a certain amount of time. Finally, the last function will just clear everything once the component is done.</p><p>The next set of functions are related to mouse movement and are way easier to understand.</p><pre>//Just update the mouse position to the references.<br>  const updateMousePosition = (event:MouseEvent) =&gt; {<br>    if(!canvas.current) return;<br>    posX.current = event.clientX - canvas.current.getBoundingClientRect().x;<br>    posY.current = event.clientY - canvas.current.getBoundingClientRect().y;<br>  }<br><br>  //When the mouse is clicked, reset the counter and set the interval to add grains<br>  //at every 20 ms.<br>  const handleMouseDown = () =&gt; {<br>    mouseIntervalRef.current = setInterval(() =&gt; {<br>      addGrain();<br>    }, 20) //Add a new grain at every 500 ms<br>  }<br><br>  //Just remove the interval and stop adding grains<br>  const handleMouseUp = () =&gt; {<br>    if(mouseIntervalRef.current) clearInterval(mouseIntervalRef.current);<br>  }</pre><p>And for the last part is our <em>JSX</em> code. It’s surprisingly simple:</p><pre>  //Our JSX is pretty simple. I am using TailwindCSS, but you don&#39;t have to.<br>  return (<br>    &lt;div className=&quot;fixed w-full h-full bg-slate-700 flex flex-col justify-center items-center&quot;&gt;<br>      &lt;div ref={canvas} <br>        onMouseDown={handleMouseDown}<br>        onMouseUp={handleMouseUp}<br>        className=&quot;bg-white h-[85%] w-[85%] flex justify-center items-center rounded-[12px] border-[3px] border-slate-800 overflow-hidden&quot;&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default App</pre><p>Done adding the code, just run the code below:</p><blockquote>npm run dev</blockquote><p>And there you are! Just click on the screen and you will see matter.js running together with React. With this base code, you can extend this and do anything you want. To get the same result from the video on the top, I just added some minor changes to the code. Look at the repository here:</p><blockquote><a href="https://github.com/marcelo-msbg/MatterJS-Article.git"><strong><em>https://github.com/marcelo-msbg/MatterJS-Article.git</em></strong></a></blockquote><p>When working with many objects in a <em>Matter.js </em>and <em>React</em> project, optimization becomes crucial to ensure smooth performance and responsiveness. One key approach is to minimize unnecessary re-renders by carefully managing state with useRef, which allows you to persist and manipulate objects without triggering component re-renders. Additionally, consider using techniques such as object pooling (for the old birds out there, think about the <a href="https://springframework.guru/gang-of-four-design-patterns/composite-pattern/"><em>Gang of Four Composite</em></a> pattern), where you reuse objects instead of constantly creating new ones, and optimizing the <em>Matter.js</em> engine settings like reducing the number of collision checks or using simpler shapes for collision detection. By combining these strategies, you can handle a high volume of objects efficiently, maintaining both performance and user experience.</p><p>And we are done for today! I hope you understand the usefulness of useRef hook and use it more often from now on. As a bonus, by changing some useState for useRef, you get a way more efficient App.</p><p>See you next time! 👋</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f57365b926e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/matter-js-with-react-and-learn-to-use-useref-effectively-8f57365b926e">Matter.js with React, and learn to use useRef() effectively.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Portals in 2024]]></title>
            <link>https://blog.stackademic.com/mastering-react-portals-in-2024-c4f920706b5e?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f920706b5e</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-portal]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 20:43:10 GMT</pubDate>
            <atom:updated>2024-01-22T01:48:46.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering React Portal in 2024</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*amPOqGFdUDqLpkCCChzDlQ.png" /></figure><p>Today, let’s explore the power of <strong>React Portals</strong>. 🚀</p><p>Every <strong>React</strong> developer already had to handle some of the following situations:</p><blockquote>Positioning a modal outside the parent component.</blockquote><blockquote>Creating some “out of the screen” functionality, such as a Toast handler, or Chat App.</blockquote><blockquote>When building some popup that covers the entire screen and is reused on several pages.</blockquote><p>Now, despite which problem you had, I bet you resorted to this solution 😅:</p><p>1 — Make the modal appended to the main <strong>HTML</strong> document <strong>position:absolute</strong> or <strong>position:fixed</strong></p><p>2 — Control <strong>CSS</strong> cascading <strong>z-index</strong> by setting values to each component on your screen.</p><p>This solution may sound solid, but there are several drawbacks:</p><blockquote>You can’t always separate the styling from the parent component from the child (modal), especially if you are reusing the same modal on several pages. Think about a Chat App or some popup.</blockquote><blockquote>If you have several configurations of <strong>z-indexes</strong> on several pages, you will probably have to randomly select indexes that make what you want. This is terrible for code reusability.</blockquote><blockquote>Another problem with z-index is that the stacking order depends also on the stacking context, making it hard to use when your scope starts to scale.</blockquote><blockquote>Your code and your styling have the same parent-child relation when it’s not really what you want. This isn’t good for code readability and separation of concerns.</blockquote><blockquote>Event Bubbling may become an issue. <strong>CSS</strong> positioning may not always propagate as expected.</blockquote><p>I think you got it. Now, what can we do?</p><p>Well, <strong>React</strong> provides a cleaver way to solve all these problems with a simple approach: Portals</p><h3><strong>What Are Portals?</strong></h3><p>A <strong>Portal</strong> is a functionality in <strong>React</strong> that allows you to create two different hierarchies: one for your components (normal tree-like structure), and the other for your styling and positioning on the <strong>DOM</strong> (<strong>Document Object Model</strong>). That way, you can separate what is being from what is shown.</p><p>As the <em>React Documentation</em> states:</p><blockquote>A portal only changes the physical placement of the DOM node. In every other way, the JSX you render into a portal acts as a child node of the React component that renders it.</blockquote><p>And how to use it? The main instruction to create a <strong>Portal</strong> is:</p><pre>createPortal(children, domNode, key?)</pre><p>Where:</p><blockquote>· children are all components that compose your modal.</blockquote><blockquote>· <strong>domNode</strong> is the element on your <strong>DOM</strong> that will be used to display your component.</blockquote><blockquote>· key (optional), used as a unique ID for your portal.</blockquote><p>And this command returns a <strong>React Node</strong>, that can be included in your <strong>JSX</strong>. Imagine this syntax as a kind of a flag: when <strong>React</strong> finds it, it’s indicative that its children must be rendered related to the <strong>domNode</strong>, and not respecting the <strong>JSX</strong> hierarchy.</p><p>Just one additional concern is regarding event propagation: despite being rendered on the <strong>domNode</strong>, events will still follow the <strong>JSX</strong> tree logic.</p><h3>How to use Portals</h3><p>Now we are going to learn how to use it. We will create a new React project together. I am assuming you already have<strong> Node.js</strong> and npm installed 🛠️.</p><p>To simplify the styling process, we will be using <strong>TailwindCSS</strong>. Open your <strong>Terminal</strong> and type:</p><pre>npx create-next-app@latest</pre><p>Then name it <strong>toast-demo, Yes</strong> to Typescript, <strong>Yes</strong> to <strong>TailwindCSS</strong>, and <strong>Yes</strong> to the src directory</p><p>Now, cd <strong>toast-demo</strong>, then open the project (I am using <em>VS Code</em>)</p><p>Inside the folder <strong>src/pages</strong>, open the <strong>index.tsx</strong> file and change it’s <strong>Home</strong> function to this:</p><pre>import { useState } from &quot;react&quot;;<br><br>export default function Home() {<br>  //Simple state. used to switch between open and closed modal<br>  const [openModal, setOpenModal] = useState(false);<br><br>  //Our Modal. Still not using React Portal<br>  //It will only display if the openModal state is TRUE.<br>  const modal = openModal &amp;&amp; (<br>    &lt;div className=&#39;bg-red-200 rounded-full p-4&#39;&gt;<br>      Hello! I am the Portal!<br>    &lt;/div&gt;<br>  );<br><br>  //Our return statement<br>  return (<br>    // Our main div. It&#39;s covering the entire screen, and keeping the elements in a flex column.<br>    &lt;div className=&quot;fixed w-full h-full flex flex-col items-center justify-center bg-white text-black gap-4&quot;&gt;<br>      {/* Just Text */}<br>      &lt;p&gt;This is the click me parent section&lt;/p&gt;<br>      {/* Our button, that opens the modal */}<br>      &lt;button<br>        className=&quot;bg-blue-400 rounded-full p-4 cursor-pointer&quot;<br>        onClick = {() =&gt; {setOpenModal(!openModal)}}&gt;<br>        Click Me to open the Modal<br>      &lt;/button&gt;<br><br>      {/* Our modal. It&#39;s not using portals yet. */}<br>      {modal}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Just a brief explanation. We are creating a main element that is fixed and covers the entire screen. It has a text element and a button, both one below the other. We are including some configuration, a text color, and a background color. We are also adding the cursor-pointer on the button for future use.</p><p>Now let’s run. Type the following command and open the <strong>localhost</strong> on your browser:</p><pre>npm run dev</pre><p>And you should see the text, the button. If you click the button, the modal will appear below the other two elements, as expected. If the inspect, we should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyY3bO2g1wotZ5vfhMv9YA.png" /><figcaption>JSX tree structure vs DOM structure — No Portals</figcaption></figure><p>As we can see, the hierarchy is preserved both in <strong>JSX</strong> and in the <strong>DOM</strong>. Our modal div is under the main <strong>&lt;div&gt;</strong>, and has the <strong>&lt;p&gt;</strong> and the <strong>&lt;button&gt;</strong> as its siblings.</p><p>Now we are going to add our <strong>Portal</strong>. Change the code to the following:</p><pre>import { createPortal } from &quot;react-dom&quot;;<br><br>...<br><br>const modal = openModal &amp;&amp; (<br>  createPortal(&lt;div className=&#39;fixed bg-red-200 rounded-full p-4&#39;&gt;<br>    Hello! I am the Portal!<br>  &lt;/div&gt;, document.body) //We are using the DOM body as our <br>);</pre><p>This time, if you run the code, you will see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKyLOkHcZe_KhWdbuykMMg.png" /><figcaption>JSX tree structure vs DOM structure — With the use of Portals</figcaption></figure><p>Look closely. A couple of important things are happening here:</p><ul><li>Now, despite our modal still being inside our main <strong>&lt;div&gt;</strong> element on <strong>JSX</strong>, it’s being rendered right under the document <strong>&lt;body&gt;</strong>, having our main <strong>&lt;div&gt;</strong> as a sibling instead of a parent.</li><li>It’s being displayed anywhere else, as we haven’t added much styling to it. As it’s at the bottom of the <strong>&lt;body&gt;</strong>, it is being displayed on top of our main <strong>&lt;div&gt;</strong>.</li><li>Last but not least, notice that the text color is not black anymore, but the default white from the <strong>NextJS</strong> project. It happens because, as we talked about previously, our portal doesn’t have to comply with its <strong>JSX</strong> parent styling, and only responds to what the document <strong>&lt;body&gt;</strong> tells it.</li></ul><p>As you can see, <strong>React Portals</strong> allow us to separate concerns regarding code logic and the <strong>DOM</strong> disposition. With this approach in mind, we can create modals that are reusable and can be instantiated on several pages with minor to no changes. Let’s finish this first part with a demonstration of how we can handle event propagation.</p><p>We can do this in several ways, but I will keep it simple and use <strong>pointer-events-none</strong> it to ignore mouse events. That said, change your modal code to the following:</p><pre>  //Our Modal. Now with React Portals<br>  //We are adding the pointer-events-none to our main div, in order to make it ignore pointer events.<br>  const modal = openModal &amp;&amp; (<br>    createPortal(&lt;div className=&#39;fixed w-full h-full bg-black bg-opacity-[80%] bg-red-200 flex items-start justify-center pointer-events-none&#39;&gt;<br>      &lt;div className=&quot;p-8 mt-8 bg-white rounded-full text-black&quot;&gt;<br>        I am a Portal, but I am also invisible to mouse clicks!<br>      &lt;/div&gt;<br>      <br>    &lt;/div&gt;, document.body) //We are using the DOM body as our <br>  );</pre><p>The use of <strong>pointer-events-none</strong> ensures that the modal ignores mouse events, allowing interaction with the elements behind it. This is particularly useful when you want to create a modal overlay that doesn&#39;t interfere with elements beneath it.</p><p>And run. Now you can see that you are still able to close the <strong>Portal</strong> by clicking the button. And if you hover over the button, the cursor will still change.</p><p>Okay, I think you know almost everything there is to know about <strong>React</strong> <strong>Portals</strong> to start using it. I just want to finish with one last (and not very used, I must agree) feature of <strong>React Portals</strong>, which is the rendering element.</p><p>Did you notice that we used <strong>document.body</strong> our <strong>Portal’s</strong> parent element? Well, we can change it if you want to. You can use some component’s reference or name.</p><pre>// Our Modal. Now with React Portals using a custom rendering element.<br>const modal = openModal &amp;&amp; (<br>  createPortal(<br>    &lt;div className=&#39;fixed bg-red-200 rounded-full p-4&#39;&gt;<br>      Hello! I am the Portal!<br>    &lt;/div&gt;, document.getElementById(&quot;your-element-id&quot;))<br>);</pre><p>And add the <strong>property id</strong> to the element you want.</p><p>And that’s it for today. I hope now you understand how to use <strong>React Portals</strong> and start using them on your next modal.</p><p>Looking forward to seeing you soon! 👋</p><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f920706b5e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-react-portals-in-2024-c4f920706b5e">Mastering React Portals in 2024</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: Mastering useContext and useReducer hooks]]></title>
            <link>https://blog.devgenius.io/react-mastering-usecontext-and-usereducer-hooks-5f05c7801213?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f05c7801213</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 14:45:07 GMT</pubDate>
            <atom:updated>2024-01-21T09:49:22.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ultimate Guide to useContext and useReducer in React</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gliwWKYbJjQNLe2XjwVL3w.png" /></figure><p>Hi, everyone!</p><p>In this article, we’ll explore two powerful hooks in <strong><em>React </em></strong>— <strong>useContext</strong> and <strong>useReducer</strong>. In summary, <strong>useContext</strong> facilitates seamless <em>global state management</em>, allowing data to flow through components without <em>prop drilling</em>. On the other hand, <strong>useReducer</strong> provides a structured approach to state modifications, ensuring controlled access and enhancing scalability.</p><p>Too complicated? 🤔</p><p>Don’t worry! If you follow along with me on this, I can guarantee you that:</p><blockquote>By the end of this read, you’ll not only comprehend why <strong>useContext</strong> and <strong>useReducer</strong> exist but also gain a deep understanding of the problems they solve. We&#39;ll explain the nuances of state management, and explore related concepts, making you confident to venture into tools like <strong>Redux </strong>and similar state management solutions.</blockquote><p>Without further ado, let’s get started!</p><h3><strong>The Problem</strong></h3><p>Imagine we have the following <strong>React </strong>component architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkewYysnJd2wrsn9QKarBQ.jpeg" /><figcaption>Our Project Architecture</figcaption></figure><p>Now consider that, to access the page <strong>&lt;RestrictedPage/&gt;</strong> and its child components, the user needs to be authenticated (assuming a generic authentication provider here, as it’s not in the scope of this article).</p><p>Also, assume that the user can only log in through the <strong>&lt;LoginPage/&gt;</strong>. Now the problem: How can the <strong>&lt;RestrictedPage/&gt;</strong> Component know whether the user is authenticated or not?</p><p>If you already understand the basic usage of hooks, like<strong>useState()</strong>, and know how to pass <strong>props</strong> down to child components, then you probably came up with a simple (but a little dirty) solution:</p><blockquote>1 — Create an authentication state inside the<strong>&lt;Main/&gt;</strong>Component</blockquote><blockquote>const [isAuth, setIsAuth] = useState(false);</blockquote><blockquote>2 — Pass the <strong>isAuth</strong>state down to the <strong>&lt;RestrictedPage/&gt;</strong>Component, which will pass it down to its children also as <em>props</em>.</blockquote><blockquote>3 — Pass the<strong>setIsAuth</strong> and isAuth to the <strong>&lt;LoginPage/&gt;</strong> as props, to be set.</blockquote><p>Great! We have a solution!</p><p>Well, not that fast… Despite looking solid for this small scope, imagine if we had to pass the <strong>isAuth</strong>prop to dozens of child components and pages. Also, imagine if we had several states to pass down to<strong>&lt;RestrictedPage/&gt;</strong>, as the page theme and user data. In both cases, our code would quickly become a mess. This is terrible for the following reasons:</p><blockquote>· <strong>Readability</strong>: We would have to separate which properties are specific to our Component and which are being just passed down.</blockquote><blockquote>· <strong>Code Maintainability</strong>: We would have to remember to always pass down all those states and functions, even if we are not planning to use them in that given Component.</blockquote><blockquote>· <strong>Separation of Concerns</strong>: We would be bundling up several unrelated states and functions. Things can get messy this way very fast.</blockquote><p>This problem is not new and appears from time to time, even when we are not doing a similar application to the problem I presented. Let’s call this problem <strong>Prop Drilling</strong>.</p><blockquote>Prop Drilling happens when a parent component passes states do its children components just to be passed down again</blockquote><p>Good, now we understand the issue. What we truly need in this case is a way to access our states and functions from anywhere in the code, something similar to a <strong><em>Global Variable </em></strong>in a conventional programming language.</p><p>The issue is that simply creating a global variable is not encouraged in React, as it causes more problems than solves. To solve that, and other <em>State Management </em>problems, <strong>React </strong>provides a solution called <strong>Context API</strong>. 🤖</p><h3><strong>What is a Context API in React</strong></h3><p>First, <em>Context </em>is a common word in programming. It means an object that holds several types of data and functions and can be accessed by several instances in your code, allowing shared information. This concept has some links with the understanding of what a <em>singleton </em>is.</p><p>By the way, a <em>singleton </em>is a design pattern that ensures a class has only one instance and provides a global point of access to that instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DxsdXRq_yJZkAKFDq-urag.png" /><figcaption>How a Singleton Works</figcaption></figure><p>Thinking of <strong>React</strong>, a <strong><em>Context AP</em></strong>I is a mechanism that allows the data to flow down to the component tree, without the need to be passed down by its components one by one. It works something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbap_pG5kKcAs6ccEok44g.jpeg" /><figcaption>How Context API Works</figcaption></figure><p><strong>Context API </strong>creates a Global State, that can be accessed by any component that is below the component that is creating it. This is fundamental to <strong>State Management</strong> in a way that we can propagate data and action through our code without any interaction from the component in the middle.</p><p>This approach improves code reusability, as <strong>Components </strong>in the middle won’t carry useless information about other components.</p><p>Last but not least, <strong>React </strong>optimizes re-renders when using Context by a mechanism called “<em>Context Memoization</em>”. For that, only components that are consuming that specific state will be called to be re-rendered.</p><p>Now that we know what and why to use it, let’s code our solution using the <strong>Context AP</strong>I in React.</p><h3><strong>How to Use useContext()</strong></h3><p>Let’s imagine we have three <em>Components</em>. We will be using the <strong>Context API</strong> to pass a <strong>isAuth</strong> state to the third <em>Component </em>directory, without any interaction from the second one. Look at the code below:</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>// Step 1: Create a Context. This syntax may seem strange, but I will explain below.<br>const AuthContext = createContext({<br>  isAuth: false,<br>  setIsAuth: () =&gt; {},<br>});<br><br>// #################################################<br>// Step 2: Create the first component, and it’s the one that will create the context<br>const FirstComponent = () =&gt; {<br>  // Our Authentication state, initializing with false.<br> // This state is the one that will be passed, together with its setState function, to all the child components.<br>  const [isAuth, setIsAuth] = useState(false); <br><br>  return (<br>    &lt; AuthContext.Provider value={{ isAuth, setIsAuth }}&gt;<br>     &lt; SecondComponent /&gt;<br>    &lt;/ AuthContext.Provider&gt;<br>  );<br>};<br>// #################################################<br><br>// #################################################<br>// Step 3: Create the component that will be in the middle, and has no function other than call our Third Component.<br>const SecondComponent = () =&gt; {<br>  return (<br>    &lt; ThirdComponent /&gt;<br>  )<br>};<br>// #################################################<br>// Step 4: Create the last component, and the one who will consume all context data.<br>// #################################################<br>const ThirdComponent = () =&gt; {<br>  // Accessing all we need from the Provider. Notice that we are passing our Context as the input to our hook, in this case, AuthContext.<br>  const { isAuth, setIsAuth } = useContext(AuthContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Auth Status is: {isAuth ? “Authenticated”: “Not Authenticated”}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setIsAuth(!isAuth)}&gt;Toggle is Auth&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>// #################################################<br><br>export default FirstComponent;</pre><p>Now the explanation:</p><blockquote>· We are calling the function <strong>createContext(initialValue)</strong> to create a <strong>Context</strong>. It must be called outside a <strong>Component</strong>, and by default has an initial value is <strong>null</strong> if nothing is provided. The initial value is somewhat of a<strong> fail-safe</strong>, for the case that no value is provided by the context and some child component tries to access it anyway.</blockquote><blockquote>· The block <strong>&lt;AuthContext.Provider value ={{…}}&gt;</strong> is where we create a relation to our child component (we are providing to them). This syntax means that any component that is inside this wrapper will be able to access the context data.</blockquote><blockquote>· The Third Component retrieves everything passed by our <strong>Provider </strong>using the hook <strong>useContext()</strong> (<strong>isAuth</strong> and <strong>setIsAuth</strong>) Pay attention to how the <strong>&lt;SecondComponent /&gt;</strong> is not doing anything, and despite that, <strong>&lt;ThirdComponent /&gt;</strong> can get all the data from the <strong>&lt;FirstComponent /&gt;</strong>.</blockquote><p>And done! Now we can access all data provided by our <strong>&lt;FirstComponent/&gt;</strong> inside our <strong>Third Component</strong>, even changing its state. And there is something big happening here:</p><blockquote>All the states passed by a <strong>Context </strong>and <strong>Provider </strong>will behave as states inside the consumer (<strong>useContext</strong>)</blockquote><p>It means that if you add <strong>isAuth</strong> state to the dependency array of an <strong>useEffect</strong> hook inside the <strong>Third Component</strong>, it will work as usual.</p><p>One direct consequence of this is that <strong>React </strong>automatically triggers re-renders to all the children components that are using this state once it changes. It can be good (as for logging out users not authenticated) and can be bad if you are relying too much on this state for calculations, <strong>useEffect</strong>, and other uses. But for these cases, it can be managed with other approaches (and <em>hooks</em>) provided by <strong>React</strong>, not in the scope of this text.</p><p>Just before we finish talking about the <strong>Context API</strong>, let’s add another functionality.</p><p>Imagine that we need to pass another state to our <em>child components</em>, unrelated to the authentication data. Suppose we want to send our webpage theme color information.</p><p>Considering that we want to separate concerns, it’s not a good idea to add this theme state to our existing <strong>AuthContext</strong>. The better approach is to have <em>two contexts</em>: one for authentication, and the other for themes. Let’s change our code to the following:</p><pre><br>import React, { createContext, useContext, useState } from “react”;<br><br>// Step 1: Create Authentication Context<br>const AuthContext = createContext();<br><br>// Step 2: Create Theme Context<br>const ThemeContext = createContext();<br><br>// #################################################<br>// Step 3: Create the FirstComponent<br>const FirstComponent = () =&gt; {<br>  // Authentication state<br>  const [isAuth, setIsAuth] = useState(false);<br><br>  // Theme state<br>  const [theme, setTheme] = useState(&quot;light&quot;);<br><br>  return (<br>    &lt;AuthContext.Provider value={{ isAuth, setIsAuth }}&gt;<br>      &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;<br>        &lt;SecondComponent /&gt;<br>      &lt;/ThemeContext.Provider&gt;<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br>// #################################################<br><br>// #################################################<br>// Step 4: Create the SecondComponent<br>const SecondComponent = () =&gt; {<br>  return (<br>    &lt;ThirdComponent /&gt;<br>  );<br>};<br>// #################################################<br><br>// #################################################<br>// Step 5: Create the ThirdComponent<br>const ThirdComponent = () =&gt; {<br>  // Accessing the Authentication context<br>  const { isAuth, setIsAuth } = useContext(AuthContext);<br><br>  // Accessing the Theme context<br>  const { theme, setTheme } = useContext(ThemeContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Auth Status is: {isAuth ? “Authenticated” : “Not Authenticated”}&lt;/p&gt;<br>      &lt;p&gt;Current Theme: {theme}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setIsAuth(!isAuth)}&gt;Toggle Auth Status&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setTheme(theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;)}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>// #################################################<br><br>export default FirstComponent;</pre><p>As you can see, we now have two providers, one inside the other. The message here is that the data from both providers are still being passed down, without interference. In that way, <strong>Context </strong>also comes in handy when the separation of concerns is an issue.</p><p>I think now you understand the power of the <strong>Context API</strong>. Let’s talk now about its advantages and disadvantages:</p><p><strong>Advantages of Using the Context API:</strong></p><blockquote><strong>Enhanced Performance with Context Memoization:</strong></blockquote><blockquote>The <strong>Context API</strong> employs a mechanism known as “Context Memoization” to optimize re-renders. This means that only components consuming specific state changes trigger re-renders, resulting in improved performance. This is particularly advantageous in scenarios where large component trees exist, as it minimizes unnecessary re-rendering across the application.</blockquote><blockquote><strong>Global State Management Simplifies Complex Scenarios:</strong></blockquote><blockquote>The ability of the <strong>Context API</strong> to create a global state simplifies state management in complex applications. When dealing with multiple states that need to be shared across numerous components, the <strong>Context API</strong> provides a centralized approach, reducing the need for intricate prop passing and enhancing code organization.</blockquote><p><strong>Disadvantages and Considerations:</strong></p><blockquote><strong>Potential Pitfalls of Excessive Context Use:</strong></blockquote><blockquote>While the <strong>Context API</strong> offers a powerful solution, it’s essential to exercise caution in its usage. Excessive reliance on context for all state management can lead to a complex and interconnected web of states. This may impact code maintainability and make it challenging to trace state changes, especially in larger codebases.</blockquote><blockquote><strong>Performance Considerations with Large Contexts:</strong></blockquote><blockquote>In scenarios where a single <strong>Context </strong>provider encompasses a large number of states, it might lead to performance concerns. Components subscribing to this context will re-render whenever any part of the context changes. Developers should carefully evaluate the size and structure of their contexts to strike a balance between simplicity and performance.</blockquote><p>Okay, that is out of the way now. But don’t leave me yet, I promised you something in the beginning, and to achieve that, this second part is very important. Let’s complete our understanding of state management with an explanation of what kind of animal is a <strong>Reducer</strong>.</p><h3><strong>What is a Reducer, and why using useReducer?</strong></h3><p>I know you don’t want to read anymore. You have everything you need from above.</p><p>But trust me, this will help you a lot by the time you start taking state management more seriously.</p><p>On our last code, there is one thing that is bothering me: any child component can change the authentication status to true or false. It may be a security breach if we have a large team working on our project, and someone now unintentionally sets the <strong>setIsAuth()</strong> function to true when building some child component.</p><p>Another problem happens if some child component sets the <strong>setTheme</strong> function to “<em>bright</em>” instead of “<em>light</em>”. 💡</p><p>Stating more broadly, our current problem is that now our child components are too powerful and can do anything to our global states. This is unsafe, and unorganized and can lead to very complicated bugs to catch.</p><p>We can always create functions and pass them instead to perform this task, but as soon as the number of states grows larger, it can become messy.</p><p>Here is where <strong>useReducer</strong> comes into play. <strong>A Reducer </strong>is a tool that “reduces” the power of its consumers (child components), defining the limits of what can be changed in the global states, and working as gatekeepers.</p><p>And not only that. Other main benefits of using a <strong><em>Reducer </em></strong>includes:</p><blockquote>· <strong>Simplified Component Structure:</strong> Unlike passing down multiple small states, a Reducer allows the transmission of a single state object, simplifying the component structure.</blockquote><blockquote>· <strong>Enhanced Scalability:</strong> Adding or reducing global states doesn’t necessitate changes in the component code. This streamlines the development process and facilitates scalability.</blockquote><p>Great, so let’s use it. Remember that we need to do two things:</p><p>· Only allow a child to set the function <strong>setIsAuth()</strong> to false, as setting it <strong>true </strong>can only be done by the &lt;<strong>Login/&gt;</strong> page.</p><p>· Only allow a child to toggle between two types of themes: “<em>light</em>” and “<em>dark</em>”</p><p>The <strong>useReducer</strong> hook has the following syntax:</p><pre>const [state, dispatch] = useReducer(reducer, initialArg, init);</pre><p>Where:</p><blockquote>· Reducer is a function, that states what can we do to the given state (our both problems from above). It can take the state (library of states) and an action as arguments. We will explain this in detail below.</blockquote><blockquote>· <strong>initialArg</strong> is the value of our initial state when the reducer is first created.</blockquote><blockquote>· <strong>init</strong> is an optional input. It is a function that will receive <strong>initialArg</strong> and return the computed initial state. Usually is not used, so the <strong>initialArg</strong> will be <strong>initialArg</strong>.</blockquote><blockquote>· The outputs are the library of state (all states we have), and the dispatch function, that allows the child components to update our states.</blockquote><p>Still with me? Don’t worry, the syntax is strange, but you will get it after seeing the example below and using it a couple of times.</p><p>Let’s modify our code to include this functionality:</p><pre>import React, { createContext, useContext, useReducer } from “react”;<br><br>// Step 1: Create Authentication Context<br>const AuthContext = createContext();<br><br>// Step 2: Create Theme Context<br>const ThemeContext = createContext();<br><br>// Step 3: Define the Reducers. Here we see some changes. <br>const authReducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case “SET_AUTH_FALSE”: //We can only set to false<br>      return { ...state, isAuth: false };<br>    default:<br>      return state;<br>  }<br>};<br><br>const themeReducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case “TOGGLE_THEME”:<br>      return { ...state, theme: state.theme === “light” ? “dark” : “light” };<br>    default:<br>      return state;<br>  }<br>};<br><br>// #################################################<br>// Step 4: Create the FirstComponent<br>const FirstComponent = () =&gt; {<br><br>// More changes here. Notice that we don’t have useState hooks any more. All the states are defined by useReducer.<br>  // UseReducer for authentication state<br>  const [authState, dispatchAuth] = useReducer(authReducer, {<br>    isAuth: false,<br>  });<br><br>  // UseReducer for theme state<br>  const [themeState, dispatchTheme] = useReducer(themeReducer, {<br>    theme: “light”,<br>  });<br><br>  return (<br>    &lt;AuthContext.Provider value={{ authState, dispatchAuth }}&gt;<br>      &lt;ThemeContext.Provider value={{ themeState, dispatchTheme }}&gt;<br>        &lt;SecondComponent /&gt;<br>      &lt;/ThemeContext.Provider&gt;<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br>// #################################################<br><br>// #################################################<br>// Step 5: Create the SecondComponent<br>const SecondComponent = () =&gt; {<br>  return &lt;ThirdComponent /&gt;;<br>};<br>// #################################################<br><br>// #################################################<br>// Step 6: Create the ThirdComponent<br>const ThirdComponent = () =&gt; {<br>  // Accessing the Authentication context<br>  const { authState, dispatchAuth } = useContext(AuthContext);<br><br>  // Accessing the Theme context<br>  const { themeState, dispatchTheme } = useContext(ThemeContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Auth Status is: {authState.isAuth ? “Authenticated” : “Not Authenticated”}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatchAuth({ type: “SET_AUTH_FALSE” })}&gt;<br>        Set Auth to False<br>      &lt;/button&gt;<br><br>      &lt;p&gt;Current Theme: {themeState.theme}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatchTheme({ type: “TOGGLE_THEME” })}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>// #################################################<br><br>export default FirstComponent;</pre><p>Now the explanation:</p><p>Let’s start with the <strong>Reducer </strong>function. Consider the generic definition:</p><pre>const myReducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case “SUM_TO_STATE”:<br>      return { ...state, myStateName: state.myStateName + action.payload};<br>    default:<br>      return state;<br>  }<br>};</pre><p>First, don’t be scared by the syntax. <strong>It is just an arrow function!</strong></p><p>It receives two arguments passed by the <strong>useReducer</strong> hook:</p><blockquote>· State: Imagine this as a library of states object, in which each property of this library is another state, defined by us when initializing the variables. In our case, we only have one property state for each <strong>Context</strong>. You can access a specific state by including <strong>state.myState</strong>.</blockquote><blockquote>· Action: Contains mainly two types of properties: “<strong>type</strong>” and “<strong>action</strong>”. Type defines what piece of code will run internally in the reducer, inside the switch statement. Action is a form to pass a value to the reducer function.</blockquote><p>Now let’s look at the content of the <strong>Reducer </strong>function:</p><p>We start with a switch-case state. Think about each <strong>case() </strong>statement as a small function, and we can select which of these functions will be called by typing the correct value on the <strong>action.type</strong> property. In our example, we only have one type, but we can have several, as below:</p><pre>const myReducer = (state, action) =&gt; {<br>  switch (action.type) {<br>    case “TYPE_0”:<br>      //Do something and return;<br>    case “TYPE_1”:<br>      //Do another thing and return;<br>. . .<br> //If nothing, just don’t do anything at all.<br>    default:<br>      return state;<br>  }<br>};</pre><p>Great, now the last part of the function is the return statement itself. Take a look at this syntax:</p><pre>return { ...state, myStateName: state.myStateName + action.payload};</pre><p>Well, what is going on here?</p><p>The <strong>Reducer </strong>function works as a <strong>setState</strong> function from the <strong>useState</strong> hook, so it will set our big state object to anything we say. Here, as we are only changing the property state <strong>myStateName</strong>, we will be using a very handy property of <em>Javascript </em>that consists of destructuring and merging again.</p><p>This code does the following: It will return our previous state with all its properties. But if its state has a property called <strong>myStateName</strong>, it will be replaced by the second part of the argument. If it doesn’t have this property, then it will be included in the final object.</p><p>For now, we can already see a great benefit of using a <strong>Reducer</strong>: We will only need to pass a big state to our <em>children </em>in the <strong>Provider </strong>value property, instead of several small states.</p><p>Now let’s talk about how the <strong>useReducer</strong> hook is called:</p><pre>  const [state, dispatch] = useReducer(myReducer, {<br>    myState: 0, // Initial Value<br>  });</pre><p>Here we initialize our <strong>Reducer</strong>. We are providing the Reducer Function (<strong>myReducer</strong>), and the initial values of each inner state. Let’s look at the two outputs of this hook:</p><blockquote>· <strong>myState</strong>: It’s just the big state object that we talked about. We will pass it via the Provider to our children’s Components. And yes, its properties behave like states and trigger re-renders.</blockquote><blockquote>· <strong>myDispatch</strong>: This is the function that our children will call every time they need to change any of our states, by setting the action object properties.</blockquote><p>The next part that changed was the <strong>Provider </strong><em>wrapper</em>. Here is the new code:</p><pre>  return (<br>    &lt;MyContext.Provider value={{ state, dispatch }}&gt;<br>        {children}<br>    &lt;/MyContext.Provider&gt;<br>  );</pre><p>We can say it’s almost the same as our example using only the <strong>Context API</strong>. But, as I said in the past paragraph, there is a huge advantage in using a Reducer: we only need to pass one state and one “<strong>setState</strong> function” (<strong>dispatch</strong>). Our code won’t need updates or changes if we include or reduce more global states and dispatch functions. This simplifies a lot the process of building the components.</p><blockquote>One great advantage of including a Reducer in your code is that you are only passing down and retrieving one state object and one dispatch function, even if your global state is composed of multiple properties</blockquote><p>The last part of our code that we need to consider is the <strong>&lt;ThirdComponent/&gt;</strong>, which instantiates our <strong>Context API</strong> and uses the global state and the dispatch function:</p><pre>const { state, dispatch } = useContext(MyContext);</pre><p>And now, to change a global state, we call the <strong>Dispatch </strong>function instead of <strong>setState</strong> as before. And it’s done like this:</p><pre>dispatch({ type: “TYPE_SOMETHING”, payload: “any payload” })}</pre><p>If we want to access our states, just do as before:</p><pre>Console.log(state.myState); //Equals to 0, as we set initially.</pre><p>The last thing about this is that our state properties work in a conventional state, for example in this <strong>useEffect</strong> hook:</p><pre>useEffect(() =&gt; {<br>  // Your effect logic here<br>}, [state.myState]);</pre><p>And we are finally at the end. I hope you have made it this far!</p><p>🎉🎉🎉</p><h3><strong>Summary</strong></h3><p>It was a long run, but you made it. Today, we explored the following themes:</p><blockquote><strong>Prop Drilling Challenge:</strong> Discussed the issue of prop drilling and its implications on code readability and maintainability.</blockquote><blockquote><strong>Introduction to Context API:</strong> Explored the Context API as a solution, introducing the concept of a Global State and its role in efficient data propagation.</blockquote><blockquote><strong>Practical Implementation with </strong><strong>useContext:</strong> Demonstrated the implementation of <strong>useContext</strong> with a step-by-step example, showcasing its ability to simplify state access across components.</blockquote><blockquote><strong>Introduction to Reducers:</strong> Introduced the concept of a Reducer as a tool for controlled state modifications and the benefits it brings to component structure and scalability.</blockquote><blockquote><strong>Secure State Management with </strong><strong>useReducer:</strong> Illustrated the usage of <strong>useReducer</strong> to ensure secure and organized global state updates, mitigating risks associated with uncontrolled access.</blockquote><blockquote><strong>Separation of Concerns with Multiple Contexts:</strong> Extended the discussion to managing multiple global states using separate contexts, addressing concerns related to theme management.</blockquote><h3><strong>Conclusion</strong></h3><p>Mastering <strong>useContext</strong> and <strong>useReducer</strong> is key to building clean, maintainable <strong>React </strong>applications. With these tools, you will be able to create complex state scenarios and transition smoothly to advanced libraries like <strong>Redux</strong>. Effective state management is not just a convenience but a fundamental skill, empowering developers to create robust, bug-free applications.</p><p>Thank you for reading to the end, and manage your global states with care!</p><p>👏👏👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f05c7801213" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/react-mastering-usecontext-and-usereducer-hooks-5f05c7801213">React: Mastering useContext and useReducer hooks</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating Arrays and Objects with useState in React: What you May Not Know]]></title>
            <link>https://blog.devgenius.io/updating-arrays-and-objects-with-usestate-in-react-what-you-may-not-know-4af169c496c0?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af169c496c0</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[usestate]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[deep-copy]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 17:12:39 GMT</pubDate>
            <atom:updated>2024-01-19T12:02:13.993Z</atom:updated>
            <content:encoded><![CDATA[<h3>React useState: The Right Way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqEt_BZAitmLomqKVebwSA.png" /></figure><p>Let’s face it: the first time we were presented with an example of <em>useState </em><strong>Hook </strong>in <strong>React</strong>, we fell a little bit overqualified to use it. The syntax is simple, the <em>setState </em>function is easy to use, and indeed this understanding holds pretty well until the moment you have to set an <em>Array </em>to a s<em>tate</em>. It is even worse when your s<em>tate </em>is a <em>structure of objects </em>with complex data. That’s the moment you realize there are some things you may not know about how <strong>Javascript </strong>and <strong>React </strong>work.</p><p>When we define a s<em>tate </em>in <strong>React</strong>, we usually do the following:</p><pre>const [state, setState] = useState(initialValue);</pre><p>Where state is your variable,<em> setState()</em> is a function used to change your State, and initialValue is the initial value that your State will hold once your component loads.</p><p>Up to this point, in practical manners, this state behaves pretty much like a variable, the only difference is that you have to call a function to change its value.</p><p>This is kind of true assuming that your <em>state </em>will hold basic <em>Data Types</em>, such as <em>numbers</em>, <em>strings</em>, and so on. Once your data starts becoming more complicated, things will go south and that’s where this article comes to aid.</p><p>We will explain two examples of increasing levels of complexity (on purpose) so that you can understand what is going on.</p><h3>Introduction to the Problem</h3><p>Assume that we have the following content in our <em>state</em>:</p><pre>Console.log(state);<br>&gt;&gt; state = [“First String”, “Second String”, …, “Last String”]</pre><p>So, we have a <em>string array</em>. That is great, but how can I change one of the <em>array </em>items, or add one item to the end of my <em>array</em>?</p><p>One possible solution is doing the following:</p><pre>//For adding to the end, just destruct the state and append the new String.<br>setState({…state, “New String”});<br><br>//Or using a temporary variable to hold it’s value, and then setting it:<br>Let tempState = state;<br>tempState[index] = “New String”; //For changing<br>or tempState = {…tempState, “New String”} //For appending<br>setState(tempState);</pre><p>And done! nothing more to show, see you next time!</p><p>Well, not so fast… Let me show you another example:</p><p>Imagine now that your state is something like this:</p><pre>state = [<br>{user: “John”, age: 25, pets: string[] johnPets},<br>{user: “Alex”, age:61, pets: string[] alexPets},<br>...<br>];</pre><p>Now, if we need to append or update any of these objects using the same code that we used before, you will soon find several issues, such as having potentially to call the <em>setState </em>function by several <strong>Components </strong>at the same time. This problem arises because of a concept that is not very well understood by many.</p><h3><strong>Copy by Value vs Copy by Reference</strong></h3><p>What many don’t know, is that there are two main forms of copying something in programming.</p><p>The first one easiest one to understand is<strong><em> copy by value</em></strong>, also the most used and needed by developers. In this case, we create a copy of the <em>object&#39;s </em>content. After that, both the original and the copy can move in separate ways, like the example below:</p><pre>let a = 5; <br>let b = a; //Copy by value<br>a = 10; //Changing a<br><br>// Now, a = 10 and b = 5</pre><p>On the other hand, <strong><em>copying by reference</em></strong> keeps both objects connected, in a way that once you change one, the other changes to. Given the previous example, if the copy was made by reference instead, then both variables would hold the value <em>10</em> in the end.</p><p>This type of copy exists in many programming languages and different forms. If you have experience with <strong>C Language</strong>, for example, you can draw some parallels with what you can do using <em>pointers</em>.</p><blockquote>For <strong>Javascript</strong>, the rule is that primitive datatypes are copied by value, while <em>objects </em>and <em>arrays </em>are copied by reference.</blockquote><p>Here is where our problem begins. But before presenting you a solution, there is another thing you need to know:</p><h3><strong>Shallow Copy vs Deep Copy</strong></h3><p>Copying by value can be further classified as <strong><em>Shallow Copy</em></strong> and <strong><em>Deep Copy</em></strong>. A shallow copy is when only the top level of a structure is copied by value, while the rest is still copied by reference. This happens when we use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"><em>spread operator</em></a>, as we did in the beginning:</p><pre>//This will still work, as our array has no nested objects inside it.<br>setState({ ...state, “New String”}); <br><br>//On the other hand, this will be problematic, as we still copying by reference the nested objects.<br>Let newObject = {user: “Mitchel”, age:15, pets: string[] mitchelPets};<br>setState({ ...state, newObject });</pre><p>This code is incorrect, as we are doing a shallow copy, so every time the <em>newObject</em> changes in one of its properties, we will get a conflict with our state.</p><p>How to solve this problem: <strong>Deep Copy</strong>.</p><p>In this case, we want to create a unique copy of all the nested content of the object (or <em>state</em>) to a new one, in a way that if I change something, There are several caveats to this, but I will present you one solution that fixes what we need and also introduces a new way to use <em>setState().</em></p><p>First, it’s good to know that the <em>setState() </em>function can also accept a functional argument. In this case, it receives a previous value of the object as input, and must return the new value to the set state, like this:</p><pre>//Where prevState is the current value of our state.<br>setState((prevState =&gt; {...}); </pre><p>There are several benefits of using this functional form, and here are some key aspects:</p><blockquote>I provide a much cleaner syntax when updating complex objects.</blockquote><blockquote>As setState() is asynchronous, using the functional form guarantees that you are using the last value of the state. Imagine having several components trying to update the same state at the same time.</blockquote><blockquote>Guarantees the correct execution order, avoiding potential <a href="https://en.wikipedia.org/wiki/Race_condition"><strong>Race Conditions</strong></a>, for example.</blockquote><p>Okay, I have already said too much. Now, to our solution:</p><p>Given our <strong>Array of Objects</strong>, we can solve the <strong><em>appending </em></strong>problem like this:</p><pre>Let newObject = { user: &quot;NewUser&quot;, age: 30, pets: [&quot;newPet1&quot;, &quot;newPet2&quot;] };<br><br>//First, create a deep copy of the object using JSON stringy and parse. You can also do this using lodash.<br>const deepCopyOfObject = JSON.parse(JSON.stringify(newObject)); <br> <br>//Set the state using the functional form.<br>setState(prevState =&gt; [...prevState, deepCopyOfObject]); </pre><p>Now, this functional form shines when we are trying to <strong><em>update </em></strong>one of the objects, given some property. This is the code:</p><pre>Let newObject = { user: &quot;John&quot;, age: 30, pets: [&quot;newPet1&quot;, &quot;newPet2&quot;] };<br><br>//Same as above<br>const deepCopyOfObject = JSON.parse(JSON.stringify(newObject)); <br><br>setState (prevState =&gt;<br>//Here we use the map operator, which will loop through the entire prevState Objects, looking for the one that matches the user we want.<br>  prevState.map(object =&gt;<br>    //For each object, we make a conditional If statement, returning the current object If different, or returning the new object If the same user key.<br>    object.user === deepCopyOfObject.user ? { ... object, ... deepCopyOfObject }: object<br>  )<br>);</pre><p>One special comment on the code <em>{ … object, … deepCopyOfObject }</em>. We could have used just <em>deepCopyOfObject</em>, but using the spread and merge approach has the advantage of also appending internal properties of the <strong>Objects </strong>when they differ, giving priority to the content of the last one (<em>deepCopyObject</em>) once they differ.</p><p>The result is that <em>setState </em>will only update the corresponding <strong>Object </strong>(<em>“John”</em>), changing every property that differs from the previous state value, and including everything that didn’t exist.</p><p>That Is It for today, I hope ended up learning a little bit more about how to use the <em>useState </em><strong>Hook </strong>in <strong>React</strong>, and also how to copy complex data in Javascript.</p><p>Hope to see you again In the future. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af169c496c0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/updating-arrays-and-objects-with-usestate-in-react-what-you-may-not-know-4af169c496c0">Updating Arrays and Objects with useState in React: What you May Not Know</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Avoid Unreadable Conditional Statements Inside your JSX in React, NextJS, or React Native]]></title>
            <link>https://blog.stackademic.com/how-to-avoid-unreadable-conditional-statements-inside-your-jsx-in-react-nextjs-or-react-native-521eda4c964f?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/521eda4c964f</guid>
            <category><![CDATA[jsx]]></category>
            <category><![CDATA[conditional-statements]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 16:50:42 GMT</pubDate>
            <atom:updated>2024-01-19T12:03:00.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>React: A New Perspective on Conditional Statements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OshYCAfX0SQrk6V66H7fQ.png" /></figure><p>Hi everyone! Today we will be talking about a subject that we must handle from time to time.</p><p>Imagine that you have a React Component, and inside it, there is the <em>return()</em> function where you put your <strong>JSX </strong>code. Now imagine that you only display that <strong>JSX </strong>under a certain set of conditions, as if some <strong>State </strong>is true, or if anything is pending, and so on.</p><blockquote><strong>Note</strong>: If you don’t know what <strong>JSX </strong>is, check the React documentation <a href="https://legacy.reactjs.org/docs/introducing-jsx.html"><strong>here</strong></a>.</blockquote><p>These are problems solved by the very basic conditional statements, such as using an <em>if </em>or <em>switch</em>.</p><p>You may have had to deal with this kind of problem in <strong>React </strong>and came up with a dirty solution like that below:</p><pre>import {React, useState} from &#39;react&#39;;<br><br>export function App(props) {<br>  const [showDivA, setShowDivA] = useState(false);<br>  const [showDivB, setShowDivB] = useState(false);<br>  const [caseState, setCaseState] = useState(0);<br><br>  return (<br>    showDivA ? (<br>      &lt;div&gt;<br>        {showDivB ? (<br>          &lt;div&gt;<br>            Content A<br>          &lt;/div&gt;<br>        ) : (<br>          &lt;div&gt;<br>            Content B<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    ) : (<br>      &lt;div&gt;<br>        {caseState === 0 &amp;&amp;<br>          &lt;div&gt;<br>            Case 0<br>          &lt;/div&gt;<br>        }<br>        {caseState === 1 &amp;&amp;<br>          &lt;div&gt;<br>            Case 1<br>          &lt;/div&gt;<br>        }<br>        // ...<br>        {caseState === 200 &amp;&amp;<br>          &lt;div&gt;<br>            Case 200<br>          &lt;/div&gt;<br>        }<br>        // ...<br>      &lt;/div&gt;<br>    )<br>  );<br>}</pre><p>Surprisingly, that code works. Despite that, you can see how hard it is to understand or write. You will be spending most of your time trying to figure out which kind or bricked (or how many) should you use.</p><p>The scariest part is that this code represents something as simple as that:</p><pre>if(showDivA) {<br> if(showDivB) return &quot;Content A&quot;<br> return &quot;Content B&quot;<br>}<br><br>switch (caseState) {<br> case 0:<br>  return &quot;Case 0&quot;<br> case 1: <br>  return &quot;Case 1&quot;<br> …<br> Case 200<br>  Return &quot;Case 200&quot;<br> …<br>}</pre><p>Image if you decide to complicate a little more. You won’t be able to read this code again when you come back next week.</p><p>Okay, the problem is understood. Now, for our solution, let’s start with a simple concept that most of beginners don’t know about React:</p><blockquote><strong>A React component is just a Function, and its content runs in sequence!</strong></blockquote><p>What does this mean? Well, once we start playing with <strong>React </strong>and how to combine <strong>Javascript </strong>with <strong>JSX </strong>syntax, we tend to think of <strong>Components </strong>as two isolated parts: The <strong>Javascript </strong>code, with all its arrow functions, hooks definition, and so on, and the second part as being everything that is inside the<em> return() </em>statement.</p><p>The reality is that it all runs in a sequence (ish). So, as any state changes and the <strong>Component </strong>is rendered (called) again, this sequence will happen again and again, triggering new information to be displayed. Check this principle in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*FBM3kuHmPXjO1gcAES3LwA.png" /><figcaption>React code runs in sequence</figcaption></figure><p>This may seem obvious, but maybe you don’t consider it when you are creating your components. One great use of this concept is when dealing with the problem that we introduced above.</p><blockquote><strong>Note</strong>: This approach works if you don’t mess with React objects, placing then where you shouldn’t. If you only play with what Javascript has, you should be fine.</blockquote><p>Let’s rewrite our code. Remember that, as the component <strong>App </strong>is a <strong>Function</strong>, we can have multiple return statements in sequence. That way, we can simplify a lot of our code by using <strong>Javascript </strong>syntax. Check the result below:</p><pre>import {React, useState} from &#39;react&#39;;<br><br>export function App(props) {<br>  const [showDivA, setShowDivA] = useState(false);<br>  const [showDivB, setShowDivB] = useState(false);<br>  const [caseState, setCaseState] = useState(0);<br><br>  if(showDivA) {<br>    if (showDivB) return (&lt;div&gt; Content A &lt;/div&gt;) //This will only be accessed If both are true<br>    else return (&lt;div&gt; Content B &lt;/div&gt;) //This will only be returned If showDivB Is false, as before<br>  }<br><br>  switch(caseState) { //We will only get here with both are false.<br>    case 0:<br>      return (&lt;div&gt; Case 0 &lt;/div&gt;)<br>    case 1:<br>      return (&lt;div&gt; Case 1 &lt;/div&gt;)<br>      // ...<br>    case 200:<br>      return (&lt;div&gt; Case 200 &lt;/div&gt;)<br>    default:<br>      return (&lt;div&gt; default &lt;/div&gt;)<br>  }<br>}</pre><p>What is happening here:</p><ul><li>The first if statement will only be accessed if the state <em>showDivA </em>is <strong>true</strong>. Otherwise, we will be dealing with the <em>switch </em>statement.</li><li>In the case that <em>showDivA </em>is <strong>true</strong>, then we have another if that is only accessed if <em>showDivB </em>is also <strong>true</strong>. Otherwise, we will fall into the second return statement.</li></ul><p>This code returns the same output, has half the number of lines of code than before, and most importantly, is way easier to read than before. This improves code reusability and maintenance, as it is way easier for another programmer and team member to understand and change it.</p><p>It’s a simple problem with several solutions, but this approach enables you to understand a little more about how <strong>React </strong>logic works and may enable you to come up with similar solutions in the future, as when thinking about where to define and call your component’s functions, <em>useEffect </em>declaration, constant values, and so on.</p><p>Thank you for reading this article. I hope to see you on the next one!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521eda4c964f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-avoid-unreadable-conditional-statements-inside-your-jsx-in-react-nextjs-or-react-native-521eda4c964f">How to Avoid Unreadable Conditional Statements Inside your JSX in React, NextJS, or React Native</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Vision Camera Frame Processor to Native Android and iOS in React Native]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@botelhomarcelo7/how-to-integrate-vision-camera-frame-processor-to-native-android-and-ios-in-react-native-7b2b3f98279f?source=rss-9fd13879ed39------2"><img src="https://cdn-images-1.medium.com/max/1024/1*0ryAVv4ojG3g9e-vpM4HXw.png" width="1024"></a></p><p class="medium-feed-snippet">Setup a Frame Processor Plugin on Native Android and iOS for a React Native project, using Vision Camera library.</p><p class="medium-feed-link"><a href="https://medium.com/@botelhomarcelo7/how-to-integrate-vision-camera-frame-processor-to-native-android-and-ios-in-react-native-7b2b3f98279f?source=rss-9fd13879ed39------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@botelhomarcelo7/how-to-integrate-vision-camera-frame-processor-to-native-android-and-ios-in-react-native-7b2b3f98279f?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2b3f98279f</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[vision-camera]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[native-modules]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 20:57:21 GMT</pubDate>
            <atom:updated>2024-01-19T12:06:27.216Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why you should avoid using useEffect hook in React and what to do instead]]></title>
            <link>https://blog.stackademic.com/why-you-should-avoid-using-useeffect-hook-in-react-and-what-to-do-instead-740660e33420?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/740660e33420</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 16:57:40 GMT</pubDate>
            <atom:updated>2024-01-16T13:19:12.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>React: You are Using useEffect() Wrong, Do This Instead</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNyXe0v36rg8X4iCpQYFag.png" /></figure><p>Once one decides to move forward with learning <strong>React</strong>, hooks are among the first things to learn (and to be frustrated with). Hooks are essential parts of <strong>React</strong>, as they were created to solve several problems that appeared in the first couple of versions of <strong>React</strong>, when every rendering was done inside the component’s lifecycle functions, such as <strong>componentDidMount()</strong>, <strong>componentWillMout(),</strong> <strong>componentDidUpdate()</strong>.</p><p>That said, the first hooks everyone starts touching are <strong>useState()</strong> and <strong>useEffect()</strong>. The first is used for state management and control when the component should be rendered again, while the second behaves somewhat similarly to the lifecycle functions stated above.</p><p>The <strong>useEffect() </strong>hook<strong> </strong>can receive two outputs: the first is a callback function, while the second is optional and defines when this hook should be called.</p><pre>  useEffect((prevProps) =&gt; { //prevProps are optional and has some specific uses. Compare with what happens with the lifecycle functions.<br> //Custom function content….<br>    custom function content…<br><br>    return () =&gt; {<br>      // Code to run when the component is unmounted or when dependencies change<br>      // It helps in avoiding memory leaks and unexpected behavior<br>    };<br>  }, [dependencies in array form]);</pre><p>One caveat that gets a lot of beginners is how the second parameter works. Here is a resume:</p><blockquote>Case A: If nothing is added, then <strong>useEffect</strong> will run at every change of state inside the current component.</blockquote><blockquote>Case B: If an empty array is added ([]), then the <strong>useEffect</strong> will run only once when the component is mounted.</blockquote><blockquote>Case C: If some array is provided ([state]), then <strong>useEffect</strong> will run every time the state changes</blockquote><blockquote>Case C*: If some array is provided ([state1, state2, ….], <strong>useEffect</strong> will run every time <strong>ANY</strong> of these states changes.</blockquote><p>Now that we’ve revisited how <strong>useEffect </strong>works, it&#39;s essential to delve into an optimization technique known as <em>memoization</em>. <em>Memoization </em>helps prevent unnecessary re-renders and can significantly enhance the performance of your components, especially when dealing with dependency arrays in <strong>useEffect</strong>.</p><p>The main idea of the <strong>useEffect</strong> hook is to synchronize data transfer with external <strong>APIs</strong> or another system, like when you are accessing a database, or waiting for an <strong>HTTP</strong> request to complete. The trouble is that we tend to use this hook in every situation possible inside our code, especially <strong>Case A</strong> and C* listed above, and the code can become incredibly unreadable with just a couple of lines of code, including triggering a loop if you change one of the states in the dependency array during the process.</p><p>This can make your code inefficient too, as useEffect works as if you were stepping aside to run some code and then coming back to the main thread. This could be more efficient.</p><p>Great, now you know that sometimes, <strong>useEffect </strong>is not the best solution. Now we will be looking at each case in detail.</p><p>Let’s talk about each one of the use cases in detail:</p><blockquote>Case A — No dependency array: This one should be abolished from your code, as it will certainly trigger unnecessary calculations every time a state changes. In this case, you should specify which states really should trigger this function using a dependency array.</blockquote><blockquote>Case B — Empty dependency array: This is one of the good ones, the only recommendation that I can provide is to keep just one of these for each component and wrap its content into a function.</blockquote><blockquote>Case C — One dependency state only. It’s ok to use if you are processing external data. Otherwise, you should change it to the solution I will provide below.</blockquote><blockquote>Case C* — Multiple dependency states in the same <strong>useEffect</strong>. This is the one I consider the most troublesome. I recommend you try to untangle the states into different useEffect hooks before anything, as it makes your code very unreadable.</blockquote><p>Now for the solution that I promised. Let’s consider these two Components (Parent and Child):</p><pre>// ParentComponent.js<br>import React, { useState, useEffect } from &#39;react&#39;;<br>import ChildComponent from &#39;./ChildComponent&#39;;<br><br>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br>  const [message, setMessage] = useState(&#39;Hello from Parent!&#39;);<br><br>useEffect(() =&gt; {<br> setMessage(`Button clicked ${count} times!`);<br>},[count]}<br><br>  return (<br>      &lt;ChildComponent count={count} message={message} setCount={setCount} /&gt;<br>  );<br>}<br><br>export default ParentComponent;<br><br><br><br>// ChildComponent.js<br>import React from &#39;react&#39;;<br><br>function ChildComponent({ count, message, setCount }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Child Component&lt;/h3&gt;<br>      &lt;p&gt;Received Count from Parent: {count}&lt;/p&gt;<br>      &lt;p&gt;Received Message from Parent: {message}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; {setCount(count+1)}&gt;Click Me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ChildComponent;</pre><p>Now let’s explain what is happening here:</p><blockquote>1 — Once the user clicks the button on the <strong>ChildComponent</strong>, we change the state “count” by incrementing 1. It will take one render loop to happen and change the state.</blockquote><blockquote>2 — Once the state “count” changes, the child component will be rendered again and it will also trigger the <strong>useEffect</strong> hook on both components, which will trigger the change in the “message” state. Again, it will only happen in the next render.</blockquote><blockquote>3 — When the “message” state changes, then another render happens in the components changing the message.</blockquote><blockquote>In this case, we ended up having two renders. It may now seem much, but it can grow at a large scale once you have more states at play.</blockquote><blockquote>Now look what happens when we make the following changes in the components:</blockquote><pre><br>// ParentComponent.js<br>import React, { useState } from &#39;react&#39;;<br>import ChildComponent from &#39;./ChildComponent&#39;;<br><br>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br>  const [message, setMessage] = useState(&#39;Hello from Parent!&#39;);<br>const incrementCount = () =&gt; {<br> setCount(count + 1);<br>setMessage(`Button clicked ${count + 1} times!`);<br>}<br><br>  return (<br>      &lt;ChildComponent count={count} message={message} <br>        callbackFunction={incrementCount} /&gt;<br>  );<br>}<br><br>export default ParentComponent;<br><br><br>// ChildComponent.js<br>import React from &#39;react&#39;;<br><br>function ChildComponent({ count, message, callbackFunction }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Child Component&lt;/h3&gt;<br>      &lt;p&gt;Received Count from Parent: {count}&lt;/p&gt;<br>      &lt;p&gt;Received Message from Parent: {message}&lt;/p&gt;<br>      &lt;button onClick={callbackFunction}&gt;Click Me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ChildComponent;<br></pre><p>We changed the code to pass a <strong>Callback Function</strong> to the Child Component. You may notice that:</p><blockquote>· We don’t have a <strong>useEffect</strong> anymore defined on the Parent Component. This makes the code easier to read, as we can understand our code as, let’s say, more linear and single-threaded than the original.</blockquote><blockquote>· We don’t have to wait for two render cycles to display our final message, or worse, render both components two times.</blockquote><blockquote>· We can separate concerns between components, making them more reusable and easier to read or adapt, as we can put whatever we want in the callback function.</blockquote><blockquote>· Both the state changes at the same time, avoiding the chaining of <strong>useEffect</strong> statements.</blockquote><p>In conclusion, the insights provided here offer valuable guidance, but it’s important to recognize that software development is a dynamic field, and solutions are not one-size-fits-all. <strong>useEffect </strong>is a very important part of <strong>React</strong>, but sometimes is not the best solution.</p><p>And that’s it for today. Thank you for reading!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=740660e33420" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-you-should-avoid-using-useeffect-hook-in-react-and-what-to-do-instead-740660e33420">Why you should avoid using useEffect hook in React and what to do instead</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VisionCamera with React Native, Frame Processor Plugin, YUV420 conversion, OpenCV, and much more]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@botelhomarcelo7/visioncamera-with-react-native-frame-processor-plugin-yuv420-conversion-opencv-and-much-more-c0736bfdd154?source=rss-9fd13879ed39------2"><img src="https://cdn-images-1.medium.com/max/1024/1*XtsMsXmoXHMX91ysEqF1Rw.png" width="1024"></a></p><p class="medium-feed-snippet">This tutorial is the first part of a series on VisionCamera for React Native. The first part goes until Frame Processor (iOS and Android)</p><p class="medium-feed-link"><a href="https://medium.com/@botelhomarcelo7/visioncamera-with-react-native-frame-processor-plugin-yuv420-conversion-opencv-and-much-more-c0736bfdd154?source=rss-9fd13879ed39------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@botelhomarcelo7/visioncamera-with-react-native-frame-processor-plugin-yuv420-conversion-opencv-and-much-more-c0736bfdd154?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0736bfdd154</guid>
            <category><![CDATA[native-modules]]></category>
            <category><![CDATA[vision-camera]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 18:54:20 GMT</pubDate>
            <atom:updated>2024-01-19T12:04:25.699Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mercado Pago API with Node.js: All You Need to Know]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.stackademic.com/mercado-pago-api-react-nextjs-e3319b6d48cf?source=rss-9fd13879ed39------2"><img src="https://cdn-images-1.medium.com/max/1023/1*CwFphrqGBf-c46FpHk_ldQ.png" width="1023"></a></p><p class="medium-feed-snippet">Hello everyone. In this article, we will build a React/NodeJS app that can create, pay, and notify payments using the Mercado Pago API.</p><p class="medium-feed-link"><a href="https://blog.stackademic.com/mercado-pago-api-react-nextjs-e3319b6d48cf?source=rss-9fd13879ed39------2">Continue reading on Stackademic »</a></p></div>]]></description>
            <link>https://blog.stackademic.com/mercado-pago-api-react-nextjs-e3319b6d48cf?source=rss-9fd13879ed39------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3319b6d48cf</guid>
            <category><![CDATA[mercadopago]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <dc:creator><![CDATA[Marcelo Botelho]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 20:51:04 GMT</pubDate>
            <atom:updated>2024-01-19T12:05:35.392Z</atom:updated>
        </item>
    </channel>
</rss>