<?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 Joao Paulo C. Marra on Medium]]></title>
        <description><![CDATA[Stories by Joao Paulo C. Marra on Medium]]></description>
        <link>https://medium.com/@joaopaulocmarra?source=rss-a4eaccf640d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IPQwfUrNn3qKyJk7yCpvhA@2x.jpeg</url>
            <title>Stories by Joao Paulo C. Marra on Medium</title>
            <link>https://medium.com/@joaopaulocmarra?source=rss-a4eaccf640d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:07:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joaopaulocmarra/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[React Clean Architecture: A Guide for Scalable, Testable Apps]]></title>
            <link>https://medium.com/@joaopaulocmarra/react-clean-architecture-a-guide-for-scalable-testable-apps-7639dbafd98a?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7639dbafd98a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 14:31:50 GMT</pubDate>
            <atom:updated>2024-02-22T14:31:50.615Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to structure your React projects for long-term success</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igXq6fdYgoivqkJnNcQTEg.jpeg" /></figure><h4><strong>Why </strong><a href="https://react.dev/"><strong>React</strong></a><strong> Developers Should Embrace Clean Architecture</strong></h4><p>React’s power lies in its ability to build dynamic and interactive user interfaces. However, as your application grows, the absence of a well-defined architecture can create a tangled mess. Intertwined logic, difficult-to-test components, and unpredictable side effects can hinder your project’s maintainability and agility.</p><p>Enter Clean Architecture. Inspired by the works of <a href="https://twitter.com/unclebobmartin">Robert C. Martin (“Uncle Bob”)</a>, this approach prioritizes maintainability, testability, and the independence of your application’s core logic from frameworks and external dependencies.</p><h3><strong>Key Concepts in Clean Architecture</strong></h3><ul><li><strong>Separation of Concerns:</strong> Each component in your application has a clear responsibility. This decoupling makes code easier to reason about, modify, and reuse.</li><li><strong>Dependency Inversion Principle:</strong> High-level modules shouldn’t depend on low-level details. Instead, core business logic depends on abstractions (e.g., interfaces), making it possible to swap out concrete implementations without breaking things.</li></ul><h3><strong>The Layers of a Clean React Application</strong></h3><h4><strong>View Layer:</strong></h4><ul><li><strong>Purpose:</strong> The View Layer’s responsibility is to translate data into the visual elements that users interact with. Think of it as the painter of your application.</li><li><strong>Keep it Simple:</strong> React components here should be as lightweight as possible, primarily concerned with displaying information and handling basic user input.</li></ul><pre>import React from &quot;react&quot;;<br><br>const BlogPost: React.FC&lt;PostViewModel&gt; = ({<br>  title,<br>  contentSnippet,<br>  readingTime,<br>}) =&gt; {<br>  return (<br>    &lt;article&gt;<br>      &lt;h2&gt;{title}&lt;/h2&gt;<br>      &lt;p&gt;{contentSnippet}&lt;/p&gt;<br>      &lt;p&gt;Estimated reading time: {readingTime} minutes&lt;/p&gt;<br>    &lt;/article&gt;<br>  );<br>};<br><br>export default BlogPost;</pre><h4><strong>UseCase Layer:</strong></h4><ul><li><strong>Function:</strong> The UseCase layer orchestrates the steps a user takes within your application, such as submitting a form, navigating between pages, or loading complex data.</li><li><strong>Data Transformation:</strong> It retrieves data from repositories and maps it into a form readily consumable by your view components (view models).</li></ul><pre>import postsRepository from &quot;@/repositories/postsRepository&quot;;<br>import calculateReadingTime from &quot;@/services/readingTimeService&quot;;<br><br>const fetchPostsUseCase = async (): Promise&lt;PostViewModel[]&gt; =&gt; {<br>  const posts: Post[] = await postsRepository.getAllPosts();<br><br>  return posts.map((post) =&gt; ({<br>    title: post.title,<br>    contentSnippet: post.content.substring(0, 100) + &quot;...&quot;,<br>    readingTime: calculateReadingTime(post.content),<br>  }));<br>};<br><br>export default fetchPostsUseCase;</pre><h4><strong>Repository Layer:</strong></h4><ul><li><strong>Mission:</strong> The Repository layer isolates your application’s core logic from the specifics of data storage. Whether it’s a local database, a cloud service, or even browser storage, the repository hides the details.</li><li><strong>API-like interface:</strong> Repositories offer a consistent way to get, change, and potentially invalidate (refresh) data.</li></ul><pre>interface PostsRepository {<br>  getAllPosts(): Promise&lt;Post[]&gt;;<br>}<br><br>export default PostsRepository; </pre><h4><strong>Adapter Layer:</strong></h4><ul><li><strong>Responsibility:</strong> The adapter is the concrete implementation of the repository interface, actually handling the network operations.</li></ul><pre>import PostsRepository from &quot;@/repositories/postsRepository&quot;;<br><br>class PostsApiAdapter implements PostsRepository {<br>  async getAllPosts(): Promise&lt;Post[]&gt; {<br>    const response = await fetch(&quot;https://jsonplaceholder.typicode.com/posts&quot;);<br>    return response.json();<br>  }<br>}<br><br>export default PostsApiAdapter;</pre><h4><strong>Service Layer:</strong></h4><ul><li><strong>Responsibility:</strong> Services encapsulate domain logic, independent of UI concerns.</li></ul><pre>const calculateReadingTime = (content: string): number =&gt; {<br>  const wordsPerMinute = 200; // Average reading speed<br>  const wordCount = content.split(&quot; &quot;).length;<br>  return Math.ceil(wordCount / wordsPerMinute);<br>};<br><br>export default calculateReadingTime;</pre><h3><strong>Conclusion</strong></h3><p>React Clean Architecture provides a robust framework for building applications that prioritize long-term maintainability and testability. By adhering to the principles of Separation of Concerns and Dependency Inversion, your code becomes more modular, less brittle, and easier to adapt as requirements evolve.</p><h4><strong>Key Takeaways</strong></h4><ul><li><strong>Think in layers:</strong> Each layer has a distinct job, fostering easier troubleshooting and updates.</li><li><strong>Interfaces are your friends:</strong> Define contracts between layers to swap implementations easily (great for testing!)</li><li><strong>Tests are essential:</strong> Clean Architecture makes it simpler to write unit, integration, and end-to-end tests, ensuring code quality.</li><li><strong>Start small, scale up:</strong> Introduce Clean Architecture principles gradually, even in existing projects.</li></ul><h4><strong>Beyond the Basics</strong></h4><p>As your application grows, consider these concepts to further enhance the architecture:</p><ul><li><strong>Event Sourcing and CQRS:</strong> Powerful patterns for complex application state management.</li><li><strong>Domain-Driven Design (DDD):</strong> Helps bridge the language gap between developers and domain experts.</li><li><strong>Dependency Injection (DI) Frameworks:</strong> Can streamline the process of wiring components together.</li></ul><h4><strong>Continuous Improvement</strong></h4><p>Clean Architecture is a journey, not a destination. Stay curious, learn from others, and don’t be afraid to experiment with different approaches. By investing in a well-structured architecture, you’ll build React applications that gracefully withstand the test of time.</p><p>The examples are simple so the article is not so long but, If you have any further questions or want to connect, feel free to check out my LinkedIn profile <a href="https://www.linkedin.com/in/joaopaulomarra/">João Paulo Marra</a>!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7639dbafd98a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Spread Operators in JavaScript Might Surprise You With Slowness (And When to Pay Attention)]]></title>
            <link>https://medium.com/@joaopaulocmarra/why-spread-operators-in-javascript-might-surprise-you-with-slowness-and-when-to-pay-attention-bbb047ce9a22?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb047ce9a22</guid>
            <category><![CDATA[spread-operator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 11:48:54 GMT</pubDate>
            <atom:updated>2024-02-16T12:03:24.404Z</atom:updated>
            <content:encoded><![CDATA[<p>The spread operator (...) is a true gem in the JavaScript syntax toolkit. It offers unparalleled elegance for combining arrays, splitting them, and updating properties within objects. Yet, it&#39;s important to know that this convenience comes with potential tradeoffs when it comes to speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pF2LK3G2pVmTF1SzUillqw.jpeg" /></figure><p><strong>The Cost of Copying</strong></p><p>Beneath the syntactic sugar, the spread operator essentially creates a shallow copy of an array or object. This isn’t free:</p><pre>const originalArray = [1, 2, 3];<br>const newArray = [...originalArray, 4]; // New array created</pre><p>With simple, small sets, the impact is negligible. But large arrays or objects demand more memory allocation and processing cycles.</p><p><strong>When Does it Matter?</strong></p><p>For small arrays and objects, the performance difference between the spread operator and traditional alternatives is likely negligible. The speed difference becomes impactful mainly when dealing with very large datasets.</p><p><strong>Proof in the Profiling</strong></p><p>Let’s time the difference (note: browser developer tools offer profiling):</p><pre>// Big array creation<br>const largeArray = new Array(100000).fill(0); <br><br>// Spread for copy<br>const startTimeSpread = performance.now();<br>const copyArraySpread = [...largeArray];<br>const endTimeSpread = performance.now();<br><br>// Traditional loop<br>const startTimeLoop = performance.now();<br>const copyArrayLoop = [];<br>for (let i = 0; i &lt; largeArray.length; i++) {<br>    copyArrayLoop.push(largeArray[i]); <br>}<br>const endTimeLoop = performance.now();<br><br>console.log(`Spread took: ${endTimeSpread - startTimeSpread}ms`);<br>console.log(`Loop took: ${endTimeLoop - startTimeLoop}ms`);</pre><p>On most devices, you’ll likely observe a performance gap.</p><p><strong>The Elegance Trade-off</strong></p><p>The spread operator promotes a more declarative, immutable style of programming. In many cases, the readability and maintainability gained are worth the slight performance overhead.</p><p><strong>Practical Concerns</strong></p><ul><li><strong>Immutability Wins:</strong> Often, spreading for pure data updates outweighs a minor performance loss.</li><li><strong>Data Volumes:</strong> Be mindful in performance-critical loops or when handling massive datasets.</li><li><strong>Premature Optimization Trap:</strong> Unless profiling proves its a bottleneck, favor spread’s clarity.</li></ul><p><strong>Alternative Approaches</strong></p><p>If you’re facing a scenario with heavy data manipulation, consider:</p><ul><li><strong>Traditional Loops:</strong> Basic loops might be better in highly performance-critical cases.</li><li><strong>Array.concat():</strong> Offers potentially faster merging of arrays.</li><li><strong>Immutable Libraries:</strong> Immutable.js provides performant data structures for situations where immutability is a core requirement.</li></ul><p><strong>In Conclusion</strong></p><p>Don’t fear the spread! Use it wisely. It shines for most use-cases, but when squeezing out every ounce of performance matters, understand the trade-offs and consider the alternatives.</p><p>If you have any further questions or want to connect, feel free to check out my LinkedIn profile <a href="https://www.linkedin.com/in/joaopaulomarra/">João Paulo Marra</a>!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb047ce9a22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a NextJS Realtime Chat with RSC and Server Actions]]></title>
            <link>https://medium.com/@joaopaulocmarra/i-built-a-nextjs-realtime-chat-with-rsc-and-server-actions-67b38534a34f?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b38534a34f</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 15:39:48 GMT</pubDate>
            <atom:updated>2023-06-09T11:28:47.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>NextJS Realtime Chat with Server Components and Server Actions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfbBuVyv56gf1DCietSh0A.png" /></figure><p>In this post, I will show you how to build a realtime chat application with <a href="https://nextjs.org/">NextJS</a>, <a href="https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components">RSC</a>, and <a href="https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions">Server Actions</a>. NextJS is a React framework that makes it easy to build server-rendered websites. <a href="https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components">RSC</a> is a new feature in NextJS that allows you to use React components on the server. <a href="https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions">Server Actions</a> are a new feature in NextJS that allows you to perform expensive tasks on the server. <a href="https://graphql.org/">GraphQL</a> is a powerful query language that allows you to fetch data from your server. <a href="https://graphql.org/blog/subscriptions-in-graphql-and-relay/#event-based-subscriptions">Subscriptions</a> are a feature of GraphQL that allows you to receive real-time updates from your server.</p><p>I will walk you through the steps of building a chat application using these technologies. I will show you how to set up your project, create your components, and write your GraphQL queries and mutations. I will also show you how to use Server Actions to perform expensive tasks on the server and how to use Subscriptions to receive real-time updates from your server.</p><p>By the end of this post, you will have a working knowledge of how to build a realtime chat application using NextJS, RSC, Server Actions, GraphQL, and Subscriptions.</p><p>I hope this helps!</p><h4>Warning: Server Actions are a new feature.</h4><p>Server Actions are a new feature in OutSystems that allow you to call server-side code from the client. This can be useful for performing complex operations or for getting real-time data from the server.</p><p>However, it is important to note that Server Actions are still under development and may not be as stable as other features. If you are using Server Actions, it is important to monitor your application for any errors or performance issues.</p><p><strong>“Why use </strong><a href="https://formidable.com/open-source/urql/"><strong>urql</strong></a><strong> subscription instead of RSC?”<br></strong>GraphQL subscriptions are a way to get real-time updates from a GraphQL server. This can be useful for things like chat applications or live dashboards. However, RSC does not yet support GraphQL subscriptions, so you cannot use them to get real-time updates from a GraphQL server.</p><h3>GitHub Repo</h3><p>I will provide you with the project repository so that you can clone it. We can then delve into each section of the code and discuss it together. Feel free to utilize the comment section to share your insights. I am eager to receive your valuable feedback on my work and learn from your experience.</p><p><a href="https://github.com/JoaoPauloCMarra/NextJS--Realtime-Chat--RSC--Server-Actions">Github Project</a></p><p>After cloning the repo in your dev machine, follow the README to setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*c5HweODb_odsrnuH9LlFoQ.png" /></figure><h3>Part 1 — GraphQL Server</h3><p>In the server part of the project, I developed a simple Apollo Server to handle chat messages. The main functionalities implemented are as follows:</p><ol><li>Fetching Messages: The frontend can retrieve all the messages by requesting the server (RSC — Retrieve All Messages).</li><li>Adding Messages: The server allows the frontend to add more messages by invoking server actions (Server Actions). The “addChat” mutation is used for this purpose, which takes the sender and message as parameters.</li><li>Real-time Updates: The frontend can subscribe to the messages and receive new ones when they are added to the server (GraphQL Subscriptions).</li></ol><p>The database used is an array stored in memory. This means that every time the server is restarted, the database will be cleared.</p><p>Now, let’s take a look at the schema definition:</p><pre>type ChatMessage {<br>  message: String!<br>  sender: String!<br>  when: String!<br>}<br><br>type Query {<br>  messages: [ChatMessage!]!<br>}<br><br>type Mutation {<br>  addChat(message: String!, sender: String!): ChatMessage!<br>}<br><br>type Subscription {<br>  messageAdded: ChatMessage!<br>}</pre><p>The schema includes the following components:</p><ul><li>ChatMessage: Defines the structure of each message.</li><li>Query messages: Retrieves all the messages from the database.</li><li>Mutation addChat: Adds new messages to the database, with the sender and message as parameters.</li><li>Subscription messageAdded: Subscribes to new messages added to the server.</li></ul><p>Moving on to the resolvers:</p><pre>import { PubSub } from &#39;graphql-subscriptions&#39;;<br><br>import { MOCK_WHEN_DATESTRING, CHAT_MESSAGES_DB } from &#39;./datasource&#39;;<br><br>const pubsub = new PubSub();<br>export const MESSAGE_ADDED = &#39;MESSAGE_ADDED&#39;;<br><br>const wait = (seconds: number): Promise&lt;void&gt; =&gt; new Promise((resolve) =&gt; setTimeout(resolve, seconds * 1000));<br><br>const resolvers = {<br>  Query: {<br>    messages: async (): Promise&lt;ChatMessage[]&gt; =&gt; {<br>      await wait(1.5); // just so the loading animation is shows in the UI<br>      return CHAT_MESSAGES_DB;<br>    },<br>  },<br>  Mutation: {<br>    addChat: async (_: unknown, { message, sender }: ChatMessage): Promise&lt;ChatMessage&gt; =&gt; {<br>      const chat = {<br>        message,<br>        sender,<br>        when: process.env.NODE_ENV === &#39;test&#39; ? MOCK_WHEN_DATESTRING : new Date().toISOString(),<br>      };<br>      CHAT_MESSAGES_DB.push(chat);<br>      pubsub.publish(MESSAGE_ADDED, { messageAdded: chat });<br>      return chat;<br>    },<br>  },<br>  Subscription: {<br>    messageAdded: {<br>      subscribe: () =&gt; pubsub.asyncIterator([MESSAGE_ADDED]),<br>    },<br>  },<br>};<br><br>export default resolvers;</pre><p>As mentioned earlier, the resolvers are designed to handle the memory database efficiently. Additionally, a MOCK setup is available for testing purposes, providing some pre-defined mock data.</p><p>To simplify the process of generating typings for the server and frontend UI, we utilize the “<a href="https://the-guild.dev/graphql/codegen">@graphql-codegen</a>” tool.</p><p>By employing this approach, we ensure that the server and frontend components are seamlessly integrated, and any modifications made to the schema are accurately reflected in the corresponding typings.</p><h3>Part 2 — NextJS UI</h3><p>I aimed to keep this section as simple as possible while developing the Chat App. To enhance understanding, I divided the components into separate files. Additionally, I relocated the pages to the components folder, which may not be optimal from a best-practice standpoint, but it serves the purpose of this project more effectively.</p><p>Regarding GraphQL communication, particularly for Query and Mutation, I implemented them in the api folder, which acts as the server in NextJS. This server handles the fetching and processing of GraphQL information, allowing the frontend to utilize it seamlessly.</p><p>To retrieve all messages using the Query, I introduced a new property to the GraphQL schema called “ChatMessage.” This property enables differentiating messages and displaying them in distinct colors within the chat frame.</p><pre>import { NextResponse } from &#39;next/server&#39;;<br>import { MUTATION_ADD_MESSAGE } from &#39;@/graphql/mutations&#39;;<br>import { QUERY_ALL_MESSAGES } from &#39;@/graphql/queries&#39;;<br><br>export const GET = async (): Promise&lt;NextResponse&gt; =&gt; {<br>  const result = await fetch(&#39;http://localhost:4000&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>    body: JSON.stringify({<br>      query: QUERY_ALL_MESSAGES,<br>    }),<br>    cache: &#39;no-store&#39;,<br>  });<br><br>  if (!result.ok) {<br>    throw Error(&#39;Failed to fetch all messages&#39;);<br>  }<br><br>  const { data } = (await result.json()) as { data: GetAllChatsResponse };<br><br>  return NextResponse.json(data.messages.map((message) =&gt; ({ ...message, old: true })));<br>};<br><br>export const POST = async (req: Request): Promise&lt;NextResponse&gt; =&gt; {<br>  const { sender, message } = (await req.json()) as AddMessageParams;<br><br>  if (!sender || sender.length &lt; 3 || !message) {<br>    return NextResponse.json({ error: true, message: &#39;No valid sender or message proided&#39; });<br>  }<br><br>  const result = await fetch(&#39;http://localhost:4000&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    },<br>    body: JSON.stringify({<br>      query: MUTATION_ADD_MESSAGE,<br>      variables: { sender, message },<br>    }),<br>    cache: &#39;no-store&#39;,<br>  });<br><br>  if (!result.ok) {<br>    throw Error(&#39;Failed to fetch all messages&#39;);<br>  }<br><br>  const { data } = (await result.json()) as { data: AddMessageResponse };<br><br>  return NextResponse.json(data);<br>};</pre><p>The code provided represents a complete Next.js server. It consists of two routes: a GET route and a POST route.</p><p>The GET route is responsible for handling queries. It allows the server to retrieve data from the GraphQL API. This route ensures smooth communication between the frontend and the server.</p><p>On the other hand, the POST route is dedicated to handling mutations. It enables the server to modify data in the GraphQL API. This route plays a crucial role in updating and managing the state of the application.</p><p>By implementing both routes, this Next.js server provides a seamless and efficient way to interact with the GraphQL API, allowing for smooth communication and data manipulation between the frontend and the server.</p><p>In this project, <a href="https://github.com/css-modules/css-modules">CSS Modules</a> were utilized for styling purposes. CSS Modules offer a convenient way to scope CSS styles to individual components, preventing style conflicts and promoting modularity.</p><p>I encourage you to explore the implementation of CSS Modules in the project and share your thoughts on its effectiveness. CSS Modules provide an organized and structured approach to styling, making it easier to maintain and understand the codebase.</p><p>Although it is possible to combine CSS Modules with Sass, for this specific project, the decision was made to refrain from using Sass. However, in other scenarios, integrating Sass with CSS Modules can offer additional features and functionalities.</p><p>It’s worth noting that this blog post will primarily focus on React Server Components and Server Actions, with an emphasis on their implementation. Other aspects of Next.js, such as <a href="https://nextjs.org/docs/app/building-your-application/routing/error-handling">error pages</a>, <a href="https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming">loading states</a>, and <a href="https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts">layouts</a>, will not be covered extensively in this particular post, allowing us to delve deeper into the key components and actions of the server and React.</p><pre>import { HomePage } from &#39;@/components/pages/Home&#39;;<br>import Providers from &#39;@/context/Providers&#39;;<br>import { SERVER_URL } from &#39;@/graphql/GraphqlClient&#39;;<br><br>const ERROR_RESPONSES = {<br>  getAllMessages: &#39;Failed to fetch all chat messages&#39;,<br>  addMessage: &#39;Failed to create a new message&#39;,<br>};<br><br>const messagesSort = (a: ChatMessage, b: ChatMessage) =&gt; {<br>  return new Date(a.when).getTime() - new Date(b.when).getTime();<br>};<br><br>const getAllMessages = async (): Promise&lt;ChatMessage[]&gt; =&gt; {<br>  const result = await fetch(`http://${SERVER_URL}/api`, {<br>    method: &#39;GET&#39;,<br>    cache: &#39;no-store&#39;,<br>  });<br><br>  if (!result.ok) {<br>    throw new Error(ERROR_RESPONSES.getAllMessages);<br>  }<br><br>  const messages = (await result.json()) as EnhancedChatMessage[];<br><br>  return messages.sort(messagesSort);<br>};<br><br>const Home = async () =&gt; {<br>  const messages = await getAllMessages();<br><br>  const addMessage = async (params: AddMessageParams) =&gt; {<br>    &#39;use server&#39;;<br><br>    const result = await fetch(`http://${SERVER_URL}/api`, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(params),<br>    });<br><br>    if (!result.ok) {<br>      throw new Error(ERROR_RESPONSES.addMessage);<br>    }<br><br>    const response = (await result.json()) as AddMessageResponse;<br><br>    return response;<br>  };<br><br>  return (<br>    &lt;Providers&gt;<br>      &lt;HomePage addMessageMutation={addMessage} initialData={messages} /&gt;<br>    &lt;/Providers&gt;<br>  );<br>};<br><br>export default Home;</pre><p>So back to It…in out app/page.tsx we added the following steps:</p><ul><li>messagesSort function: could be done in both api/route.ts or here. I prefer to let the client side handle sorting as It is not doing any real database action.</li><li>getAllMessages function: is out fetch(GET) to the NextJS Server.</li><li>The whole Home Server Component is our / route rendering the Home Page after a response from getAllMessages is complete. While this is happening the app/loading.tsx will be shown.</li><li>Inside our Home Server Component we also add a Server Action, called addMessage to handle ChatInput submissions.</li><li>We then render our HomePage with the server data and the Server Action provided to It.</li></ul><p>The components/pages/Home/Home.tsx file serves as our client component, responsible for managing side effects and rendering the child components to deliver a complete application experience to the client.</p><p>Within the application, you will notice the inclusion of a Header component. This component takes charge of rendering the appropriate view for both authenticated users and guests. Since the app follows a single-page application (SPA) architecture, all the necessary components are contained within the Home page itself. This approach was chosen to streamline the authentication process and simplify the user experience.</p><p>By consolidating the components and logic within the Home page, we aim to provide a cohesive and intuitive user interface. The Home component takes care of handling side effects, such as API requests, and manages the state transitions and rendering of child components accordingly. This design choice contributes to a more straightforward and seamless navigation experience for the user.</p><p>Our authentication process uses Context API and localStorage to happen and can be found in the context folder.</p><p>The whole graphql data is inside the graphql folder, with the <a href="https://formidable.com/open-source/urql/">urql</a>client.<br>mutations, queries, and subscriptions are separated by file.</p><pre>export const QUERY_ALL_MESSAGES = `<br>  query ChatMessages {<br>    messages {<br>      message<br>      sender<br>      when<br>    }<br>  }<br>`;<br><br>export const MUTATION_ADD_MESSAGE = `<br>  mutation AddChat($message: String!, $sender: String!) {<br>    addChat(message: $message, sender: $sender) {<br>      message<br>      sender<br>    }<br>  }<br>`;<br><br>export const SUB_NEW_MESSAGE = `<br>  subscription NewMessage {<br>    messageAdded {<br>      message<br>      sender<br>      when<br>    }<br>  }<br>`;</pre><p>Now back to the components/pages/Home/Home.tsx file. On this client page, we handle our GraphQL Subscription:</p><pre>...<br>const [subResult] = useSubscription(<br>    { query: SUB_NEW_MESSAGE },<br>    (messages: ChatMessage[] = initialData, response: { messageAdded: ChatMessage }) =&gt; {<br>      return [...messages, response.messageAdded];<br>    },<br>  );<br>...</pre><p>Next, we have the Chat component, which receives the initial set of messages from the backend and handles any new messages added thereafter:</p><pre>messages={subResult.data || initialData}</pre><p>Additionally, the Chat component is equipped with the addMessageMutation, which enables it to invoke the Server Action when a new message is sent by the user.</p><h3>Conclusion</h3><p>To summarize, this article focused on building a real-time chat application using NextJS, React Server Components (RSC), and Server Actions. NextJS, a powerful React framework, provided the foundation for server-rendered websites. RSC allowed us to leverage React components on the server, while Server Actions facilitated the execution of server-side tasks. GraphQL, a flexible query language, played a crucial role in fetching data from the server, and Subscriptions enabled real-time updates.</p><p>Throughout the article, we explored the step-by-step process of building the chat application, including project setup, component creation, and GraphQL query and mutation implementation. We also examined how Server Actions handled complex server-side operations and how Subscriptions facilitated real-time updates from the server.</p><p>By the end of the article, readers gained practical knowledge of building a real-time chat application using NextJS, RSC, Server Actions, GraphQL, and Subscriptions. The provided GitHub repository allowed for easy access to the project code, fostering collaborative learning and feedback.</p><p>It’s important to note that Server Actions are a new feature and may still undergo development. Monitoring for potential errors or performance issues is advised when utilizing Server Actions in production.</p><p>The Home component served as the client-side component, managing side effects and rendering child components for a comprehensive user experience. The inclusion of the Header component catered to both authenticated users and guests, streamlining the authentication process. The integration of GraphQL communication, including queries and mutations, was handled in the api folder, while the Chat component received initial and new messages from the backend and utilized the addMessageMutation to invoke the Server Action when a user sent a new message.</p><p>By leveraging the concepts and technologies presented in this article, readers gained the necessary skills to build their own real-time chat applications, incorporating NextJS, RSC, Server Actions, GraphQL, and Subscriptions to create dynamic and interactive user experiences.</p><h4>Your feedback and suggestions are highly valued!</h4><p>I would love to hear your thoughts on the real-time chat application built using NextJS, React Server Components, and Server Actions. Did you find the article helpful in understanding these technologies and their integration? Were the explanations clear and easy to follow?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b38534a34f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Next.js 13: A Game-Changer in Web Development]]></title>
            <link>https://medium.com/@joaopaulocmarra/exploring-next-js-13-a-game-changer-in-web-development-379184e4b72c?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/379184e4b72c</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 08:01:49 GMT</pubDate>
            <atom:updated>2023-04-19T08:01:49.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGq3enrJ8W9jGQuI7ciorg.png" /></figure><h3>Introduction:</h3><p>Next.js, the popular React framework for building server-rendered React applications, has been a game-changer in the world of web development. With its latest release, Next.js 13, there are exciting new features and improvements that web developers need to be aware of. In this blog post, we’ll dive into Next.js 13 and explore its key features, benefits, and how it can enhance your web development workflow. So, whether you’re a seasoned Next.js developer or just getting started, let’s explore the latest and greatest in Next.js 13!</p><h3>What’s New in Next.js 13:</h3><p>Next.js 13 brings a host of new features and improvements that make it even more powerful and efficient for building modern web applications. Let’s take a closer look at some of the key highlights of Next.js 13.</p><h3>Code Splitting and Dynamic Imports:</h3><p>One of the major improvements in Next.js 13 is the enhanced code splitting and dynamic imports feature. This allows you to load only the code that is needed for a particular page or component, reducing the initial load time of your application and improving performance. With Next.js 13, you can easily create dynamic imports using the import() function, making your application more optimized and efficient.</p><h3>Next.js Image Optimization:</h3><p>Images play a crucial role in web development, and Next.js 13 introduces powerful image optimization features. With the new Image component, you can easily optimize and serve images in different formats, such as WebP, AVIF, and JPEG, based on the browser&#39;s support. This can significantly improve the loading speed of your web pages and provide a better user experience.</p><h3><strong>Improved Development Experience:</strong></h3><p>Next.js 13 brings several enhancements to the development experience. The new next dev command provides a local development environment with live preview, allowing you to see changes in your code in real-time without having to refresh the page. This can greatly streamline your development workflow and increase productivity.</p><h3>Next.js Live Preview:</h3><p>Next.js 13 introduces the Next.js Live Preview feature, which allows you to preview changes to your application in a separate window as you code. This makes it easier to see the impact of your changes in real-time and iterate quickly, without needing to constantly switch back and forth between different windows or tabs.</p><h3>Enhanced Performance:</h3><p>Performance is crucial for web applications, and Next.js 13 focuses on improving performance in multiple areas. With features like automatic static optimization, server components, and optimized image serving, Next.js 13 helps you build faster, more efficient, and highly performant web applications.</p><h3>SEO Best Practices:</h3><p>Next.js 13 also includes built-in SEO optimizations to help improve the search engine visibility of your web pages. With features like automatic generation of robots.txt and sitemap.xml files, customizable document &lt;head&gt; tags, and support for Open Graph and Twitter cards, Next.js 13 makes it easy to implement SEO best practices and boost your website&#39;s search engine rankings.</p><h3>Server-side Rendering (SSR) with Next.js:</h3><p>One of the key features of Next.js is its ability to perform server-side rendering (SSR) out of the box. SSR allows you to generate dynamic HTML on the server and send it to the client, which provides a faster initial page load and improved SEO. With Next.js 13, SSR has been further optimized, allowing you to create blazing-fast web applications that deliver a seamless user experience.</p><p>Here’s an example of how you can implement SSR in Next.js 13:</p><pre>// pages/index.js<br>import React from &quot;react&quot;;<br><br>const HomePage = ({ data }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello, Next.js 13!&lt;/h1&gt;<br>      &lt;p&gt;{data}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export async function getServerSideProps() {<br>  const res = await fetch(&quot;https://api.example.com/data&quot;);<br>  const data = await res.json();<br><br>  return {<br>    props: {<br>      data,<br>    },<br>  };<br>}<br><br>export default HomePage;</pre><p>In the above code snippet, we’re using the getServerSideProps function provided by Next.js to fetch data on the server and pass it as props to the HomePage component. This way, the data is pre-rendered on the server and sent to the client as part of the initial HTML, resulting in faster page loads and improved SEO.</p><h3>Static Site Generation (SSG) with Next.js:</h3><p>Another powerful feature of Next.js is static site generation (SSG), which allows you to generate static HTML files at build time that can be served by a CDN for lightning-fast page loads. With Next.js 13, SSG has been further optimized, providing improved performance and scalability for your web applications.</p><p>Here’s an example of how you can implement SSG in Next.js 13:</p><pre>// pages/blog/[slug].js<br>import React from &quot;react&quot;;<br><br>const BlogPost = ({ post }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{post.title}&lt;/h1&gt;<br>      &lt;p&gt;{post.content}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export async function getStaticPaths() {<br>  // Fetch blog post slugs from API or database<br>  const slugs = await fetch(&quot;https://api.example.com/blog/posts&quot;);<br>  const paths = slugs.map((slug) =&gt; ({<br>    params: { slug },<br>  }));<br><br>  return {<br>    paths,<br>    fallback: false,<br>  };<br>}<br><br>export async function getStaticProps({ params }) {<br>  // Fetch blog post data from API or database based on the slug<br>  const res = await fetch(&quot;https://api.example.com/blog/posts/${params.slug}&quot;);<br>  const post = await res.json();<br><br>  return {<br>    props: {<br>      post,<br>    },<br>  };<br>}<br><br>export default BlogPost;</pre><p>In the above code snippets, we have a ServerComponent and a ClientComponent. The ServerComponent contains server-side logic and is rendered on the server, while the ClientComponent contains client-side logic and is rendered on the client. This way, you can optimize the performance of your web applications by offloading server-side logic to the server components and reducing the amount of JavaScript that needs to be sent to the client.</p><h3>Server Components</h3><p>Next.js 13 introduces an exciting new feature called Server Components, which allows developers to offload server-side logic to the server, reducing the amount of JavaScript that needs to be sent to the client and optimizing performance and scalability.</p><h4>What are Server Components in Next.js 13?</h4><p>Server Components are a new addition to the Next.js ecosystem that provides a way to encapsulate server-side logic in a component that is rendered on the server. This allows you to offload server-side logic, such as data fetching or API calls, to the server, reducing the amount of JavaScript that needs to be sent to the client and optimizing the performance and scalability of your web applications.</p><p>Server Components are similar to regular React components, but with some key differences. Server Components are rendered on the server and are not sent to the client as JavaScript code. Instead, they are rendered as plain HTML, which makes them highly efficient and scalable. Server Components can be used in conjunction with other Next.js features like Static Site Generation (SSG) or Server-Side Rendering (SSR) to further optimize the performance of your web applications.</p><p>Using Server Components with a Fetch Example:</p><pre>// components/ServerComponent.js<br>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const ServerComponent = () =&gt; {<br>  const [posts, setPosts] = useState([]);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await fetch(<br>          &quot;https://jsonplaceholder.typicode.com/posts&quot;<br>        );<br>        const data = await response.json();<br>        setPosts(data);<br>      } catch (error) {<br>        console.error(&quot;Error fetching data:&quot;, error);<br>      }<br>    };<br><br>    fetchData();<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Server Component&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {posts.map((post) =&gt; (<br>          &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ServerComponent;</pre><p>In the above code, we’re using a Server Component called ServerComponent that fetches data from the &quot;<a href="https://jsonplaceholder.typicode.com/posts">https://jsonplaceholder.typicode.com/posts</a>&quot; API using the fetch function. The fetched data is then rendered as a list of post titles in the component.</p><p>Next, let’s use the ServerComponent in our main component and see how it can be rendered on the client.</p><pre>// pages/index.js<br>import React from &quot;react&quot;;<br>import ServerComponent from &quot;../components/ServerComponent&quot;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to Next.js 13 Server Components!&lt;/h1&gt;<br>      &lt;ServerComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;</pre><h3>Conclusion:</h3><p>Next.js 13 is a game-changer in the world of web development, with its advanced features and optimizations for server-side rendering (SSR), static site generation (SSG), server components, and client components. With Next.js 13, you can create blazing-fast web applications that deliver a seamless user experience while optimizing performance and scalability. So why wait? Dive into the exciting world of Next.js 13 and unleash the power of modern web development!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=379184e4b72c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS Tutorial for Beginners & Advanced CSS Techniques]]></title>
            <link>https://medium.com/@joaopaulocmarra/css-tutorial-for-beginners-advanced-css-techniques-bba9859e119?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba9859e119</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 08:01:27 GMT</pubDate>
            <atom:updated>2023-04-18T08:01:27.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HdU823-ZuVNOTnas.png" /></figure><h3>Introduction:</h3><p>CSS (Cascading Style Sheets) is a powerful tool for designing web pages and creating stunning visual effects. Whether you are a beginner or an experienced web developer, learning advanced CSS techniques can help you take your web design skills to the next level. In this blog post, we will explore some advanced CSS techniques and provide a tutorial for beginners to get started with CSS. From essential concepts to practical examples, this blog post will guide you through the world of CSS with a focus on maximizing SEO practices.</p><h3>Understanding CSS Basics:</h3><p>Before diving into advanced CSS techniques, it’s crucial to have a solid understanding of CSS basics. CSS involves styling HTML elements using rules that define how elements should be displayed on a web page. CSS selectors, properties, and values are used to create visually appealing web pages.</p><h3>Advanced CSS Techniques:</h3><ol><li><strong>Flexbox &amp; Grid Layout:</strong> Flexbox and Grid Layout are powerful CSS techniques that allow you to create complex layouts with ease. Flexbox is a one-dimensional layout system that provides flexible options for distributing space among items in a container. Grid Layout, on the other hand, is a two-dimensional layout system that allows you to create both rows and columns, making it perfect for creating complex grid-based designs.</li><li><strong>CSS Transitions &amp; Animations:</strong> CSS Transitions and Animations allow you to add smooth transitions and animations to elements on your web page. Transitions enable you to change property values smoothly over time, while Animations provide more complex and dynamic animations with keyframes and timing functions.</li><li><strong>Pseudo-classes &amp; Pseudo-elements:</strong> Pseudo-classes and Pseudo-elements are special selectors in CSS that allow you to target specific states or parts of an element. Pseudo-classes are used to style elements based on their state, such as :hover, :active, or :focus. Pseudo-elements, on the other hand, allow you to style specific parts of an element, such as ::before or ::after.</li></ol><h3>CSS Tutorial for Beginners:</h3><p>If you’re new to CSS, here’s a tutorial to get you started:</p><ol><li><strong>CSS Selectors &amp; Properties:</strong> CSS Selectors are used to target HTML elements and apply styles to them. In this tutorial, we will cover commonly used selectors such as element selectors, class selectors, and ID selectors, along with essential CSS properties like color, font-size, margin, and padding.</li><li><strong>Box Model &amp; Layout:</strong> Understanding the CSS Box Model is crucial for designing web pages. It includes the content area, padding, margin, and border of an element. In this tutorial, we will cover the Box Model and layout techniques like float, positioning, and display properties.</li><li><strong>Responsive Design &amp; Media Queries:</strong> With the increasing use of mobile devices, responsive design has become essential. We will cover how to create responsive designs using media queries, which allow you to apply different styles based on the screen size or device.</li></ol><h3>SEO Best Practices for CSS:</h3><p>While CSS is primarily a styling language, it can still impact SEO. Here are some best practices to consider when using CSS for web design:</p><ol><li><strong>Use External CSS Files:</strong> It’s important to keep your CSS code in external files rather than inline or embedded in HTML. This allows for better separation of concerns and makes it easier for search engines to crawl and understand your web pages.</li><li><strong>Optimize CSS Code:</strong> Make sure your CSS code is optimized for performance. This includes minimizing the use of unnecessary selectors, reducing the number of CSS files, and compressing CSS files to reduce file size.</li><li><strong>Use Semantic Markup:</strong> Use semantic HTML markup and CSS class names that reflect the content and purpose of the elements. This helps search engines understand the structure and meaning of your web pages, improving SEO.</li><li><strong>Responsive Design:</strong> Design your web pages with a responsive layout that adapts to different screen sizes and devices. This ensures that your web pages are accessible and user-friendly on all devices, including desktops, tablets, and mobile phones.</li><li><strong>Proper Use of Heading Tags:</strong> Use heading tags (H1, H2, H3, etc.) to structure your content logically and semantically. This helps search engines understand the hierarchy and importance of your content.</li><li><strong>Alt Text for Images:</strong> Use descriptive alt text for images in your web pages. This helps with accessibility for visually impaired users and also provides additional context for search engines to understand the content of your images.</li></ol><h3>Some code examples</h3><h4>Flexbox</h4><pre>.container {<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>}<br>.item {<br>  flex: 1;<br>  padding: 1rem;<br>}</pre><h4>Grid Layout</h4><pre>.container {<br>  display: grid;<br>  grid-template-columns: repeat(3, 1fr);<br>  grid-gap: 1rem;<br>}<br>.item {<br>  grid-column: span 1;<br>  grid-row: span 1;<br>  padding: 1rem;<br>}</pre><h4>Transition</h4><pre>.button {<br>  background-color: #f00;<br>  color: #fff;<br>  padding: 1rem;<br>  transition: background-color 0.3s ease;<br>}<br>.button:hover {<br>  background-color: #00f;<br>}</pre><h4>Animation</h4><pre>@keyframes rotate {<br>  from {<br>    transform: rotate(0deg);<br>  }<br>  to {<br>    transform: rotate(360deg);<br>  }<br>}<br>.spin {<br>  animation: rotate 2s infinite linear;<br>}</pre><h4>Responsive Design</h4><pre>.container {<br>  display: flex;<br>  flex-wrap: wrap;<br>}<br>.item {<br>  flex: 1;<br>  padding: 1rem;<br>  box-sizing: border-box;<br>}<br>@media (min-width: 768px) {<br>  .item {<br>    flex-basis: 50%;<br>  }<br>}<br>@media (min-width: 1024px) {<br>  .item {<br>    flex-basis: 33.33%;<br>  }<br>}</pre><h3><strong>Conclusion:</strong></h3><p>In this blog post, we covered advanced CSS techniques, including Flexbox, Grid Layout, Transitions, and Animations, as well as a CSS tutorial for beginners, covering selectors, properties, Box Model, layout, and responsive design. We also discussed SEO best practices for CSS, including using external CSS files, optimizing CSS code, using semantic markup, and designing with responsiveness in mind. By following these best practices, you can create visually appealing web pages that are optimized for SEO and provide a great user experience.</p><p>If you have any further questions or want to connect, feel free to check out my LinkedIn profile <a href="https://www.linkedin.com/in/joaopaulomarra/">João Paulo Marra</a>!</p><p>Happy coding!</p><h4>References:</h4><ol><li>CSS-Tricks — Flexbox: <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">https://css-tricks.com/snippets/css/a-guide-to-flexbox/</a></li><li>MDN Web Docs — Grid Layout: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/grid">https://developer.mozilla.org/en-US/docs/Web/CSS/grid</a></li><li>CSS Transitions and Animations: <a href="https://css-tricks.com/almanac/properties/t/transition/">https://css-tricks.com/almanac/properties/t/transition/</a></li><li>MDN Web Docs — Pseudo-classes: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes">https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes</a></li><li>MDN Web Docs — Pseudo-elements: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements">https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements</a></li><li>MDN Web Docs — Responsive Design: <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design">https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design</a></li><li>Google Developers — SEO Starter Guide: <a href="https://developers.google.com/search/docs/beginner/seo-starter-guide">https://developers.google.com/search/docs/beginner/seo-starter-guide</a></li><li>CSS Optimization Tips: <a href="https://css-tricks.com/optimizing-css-for-better-performance/">https://css-tricks.com/optimizing-css-for-better-performance/</a></li><li>Alt Text for Images: <a href="https://www.w3.org/WAI/tutorials/images/decision-tree/">https://www.w3.org/WAI/tutorials/images/decision-tree/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba9859e119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Context API: A Comprehensive Tutorial for Front-end Developers]]></title>
            <link>https://medium.com/@joaopaulocmarra/mastering-react-context-api-a-comprehensive-tutorial-for-front-end-developers-ed147491eec6?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed147491eec6</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 00:01:39 GMT</pubDate>
            <atom:updated>2023-04-18T00:01:39.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uVA437jc2Of1xwGPWbk0WA.png" /></figure><h3>Introduction:</h3><p>Welcome to a comprehensive tutorial on mastering React Context API, one of the most powerful features in React for managing global state and prop drilling. In this tutorial, we will explore the ins and outs of React Context API, its key concepts, and how it can be used to simplify state management in complex React applications. Whether you are a seasoned React developer looking to level up your skills or a beginner just starting out, this tutorial is for you. So let’s dive in!</p><h3>What is React Context API?</h3><p>React Context API is a built-in feature in React that allows for sharing state across different components in a tree-like structure, without the need for prop drilling. It provides a way to pass data from a parent component down to multiple levels of child components, without explicitly passing props through each intermediate component.</p><h3>Why Use React Context API?</h3><p>React Context API offers several advantages over traditional prop drilling, making it a powerful tool for managing global state in large React applications. Some key benefits of using React Context API include:</p><ul><li>Simplified state management: Context API allows for centralizing state management and eliminates the need for passing props through multiple levels of components, making code cleaner and more maintainable.</li><li>Improved performance: Context API avoids unnecessary re-renders by only updating components that depend on the changed context values, resulting in better performance compared to prop drilling.</li><li>Scalability: Context API is highly scalable and can be used to manage complex global state in large applications, making it a preferred choice for managing state in complex React projects.</li></ul><h3>How to Create and Use Context in React</h3><p>Creating and using context in React is easy and straightforward. Here are the steps to create and use context in your React application:</p><ol><li>Create a context object: To create a context object, use the React.createContext() function, which returns a context object with a Provider and a Consumer component.</li><li>Set up the Provider component: The Provider component is used to wrap the parent component(s) that will provide the context to its child components. It takes a value prop, which is used to pass the data to the child components.</li><li>Access the context using the Consumer component: The Consumer component is used to access the context data in any child component. It takes a function as its child, which receives the context data as an argument.</li><li>Use the useContext Hook: In addition to the Consumer component, you can also use the useContext hook to access the context data in a functional component directly.</li></ol><p>Provider and Consumer Components in Context API The Provider and Consumer components are the two main components used in React Context API.</p><p>The Provider component is used to wrap the parent component(s) that will provide the context data. It takes a value prop, which is used to pass the data to the child components. Here&#39;s an example of how to use the Provider component:</p><pre>import React from &quot;react&quot;;<br><br>const MyContext = React.createContext();<br><br>const App = () =&gt; {<br>  const data = { name: &quot;John&quot;, age: 25, city: &quot;New York&quot; };<br><br>  return (<br>    &lt;MyContext.Provider value={data}&gt;<br>      &lt;ChildComponent /&gt;<br>    &lt;/MyContext.Provider&gt;<br>  );<br>};<br><br>export default App;</pre><p>In the above example, the MyContext.Provider component is used to wrap the ChildComponent, which will have access to the data object passed as the context value.</p><p>The Consumer component is used to access the context data in any child component. It takes a function as its child, which receives the context data as an argument. Here’s an example of how to use the Consumer component:</p><pre>import React from &quot;react&quot;;<br><br>const MyContext = React.createContext();<br><br>const ChildComponent = () =&gt; {<br>  return (<br>    &lt;MyContext.Consumer&gt;<br>      {data =&gt; (<br>        &lt;div&gt;<br>          &lt;h1&gt;{data.name}&lt;/h1&gt;<br>          &lt;p&gt;{data.age} years old&lt;/p&gt;<br>          &lt;p&gt;City: {data.city}&lt;/p&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/MyContext.Consumer&gt;<br>  );<br>};<br><br>export default ChildComponent;</pre><p>In the above example, the MyContext.Consumer component is used to access the data object passed as the context value, and it renders the relevant data in the child component.</p><h3>Using useContext Hook for Context API</h3><p>In addition to the Consumer component, you can also use the useContext hook to access the context data in a functional component directly. Here&#39;s an example of how to use the useContext hook:</p><pre>import React, { useContext } from &quot;react&quot;;<br><br>const MyContext = React.createContext();<br><br>const ChildComponent = () =&gt; {<br>  const data = useContext(MyContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{data.name}&lt;/h1&gt;<br>      &lt;p&gt;{data.age} years old&lt;/p&gt;<br>      &lt;p&gt;City: {data.city}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ChildComponent;</pre><p>In the above example, the useContext hook is used to access the data object passed as the context value directly in the functional component.</p><h3>Best Practices for Using React Context API</h3><p>While React Context API is a powerful tool for managing global state, it’s important to follow some best practices to ensure optimal usage. Here are some best practices for using React Context API:</p><ol><li>Use Context API for global state: Context API is designed for managing global state that needs to be accessed by multiple components in a React application. Avoid using it for local component state or for passing props between parent and child components, as there are other more suitable alternatives for those use cases.</li><li>Keep context values small and simple: Context values should be kept small and simple, containing only the necessary data that needs to be shared across components. Avoid passing complex objects or large data sets as context values, as it can lead to performance issues.</li><li>Use Provider component judiciously: The Provider component should be used judiciously and only where needed. Avoid wrapping too many components with Provider, as it can lead to unnecessary re-renders and performance degradation. Instead, wrap only the necessary parent component(s) that need to provide the context data.</li><li>Optimize Consumer component usage: While the Consumer component provides a way to access context data in any child component, excessive usage of Consumer components can also lead to performance issues. Use it only where necessary, and consider using the useContext hook for more efficient and concise code.</li><li>Follow React’s recommended pattern for context updates: When updating context data, follow React’s recommended pattern of using a callback function with the setState method to ensure accurate and reliable updates. Avoid directly mutating the</li><li>Keep context separate from presentation logic: It’s best to keep the context separate from the presentation logic of your components. Context should be used for managing state and data, while presentation logic should be handled in separate components. This promotes separation of concerns and makes your codebase more maintainable and scalable.</li><li>Optimize context updates with memoization: To optimize performance, you can use memoization techniques like React.memo or useMemo hook to prevent unnecessary re-renders of components that consume context data. This can help improve the performance of your application, especially when dealing with large or complex context data.</li><li>Test context-driven components thoroughly: When using React Context API, it’s important to thoroughly test components that consume context data. This includes testing different scenarios and edge cases to ensure that the components behave as expected when consuming context data from different providers or when the context data updates.</li></ol><p>Conclusion React Context API is a powerful tool for managing global state in a React application. It provides a way to pass data down the component tree without the need for props drilling, making it more convenient and efficient. By following best practices, such as using context for global state, keeping context values small and simple, optimizing context updates, and thoroughly testing components, you can effectively use React Context API to manage the state in your React applications.</p><p>I hope this tutorial has provided you with a solid understanding of React Context API and how to use it in your applications. If you have any further questions or need more clarification, feel free to ask in the comments below or connect with me on LinkedIn at <a href="https://www.linkedin.com/in/joaopaulomarra/">https://www.linkedin.com/in/joaopaulomarra/</a>.</p><p>Thank you for reading and happy coding!</p><p>Keywords: React Context API, tutorial, global state management, useContext, Provider, Consumer, best practices, memoization, performance optimization, testing.</p><p>Links:</p><ol><li><a href="https://react.dev/docs/context.html">React Context API Documentation</a></li><li><a href="https://react.dev/docs/react-api/react/memo">React.memo Documentation</a></li><li><a href="https://react.dev/docs/hooks-reference.html#usememo">useMemo Hook Documentation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed147491eec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering React Hooks useEffect: Best Practices for Efficient State Management and Side Effects]]></title>
            <link>https://medium.com/@joaopaulocmarra/mastering-react-hooks-useeffect-best-practices-for-efficient-state-management-and-side-effects-d3cf64710c15?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3cf64710c15</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 14:11:37 GMT</pubDate>
            <atom:updated>2023-04-17T14:11:37.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN_8xRcRF_pDhk_zVshq-g.png" /></figure><h3>Introduction:</h3><p>Welcome to our comprehensive guide on mastering React Hooks useEffect! If you’re a React developer, you’re likely familiar with the power of useEffect, which allows you to manage side effects and handle state changes in functional components. However, to truly harness the full potential of useEffect, it’s important to follow best practices to ensure efficient and effective state management in your React applications. In this blog post, we will delve into the best practices for using useEffect, with practical examples and tips to optimize your code for performance and maintainability.</p><p>Best Practices for Using useEffect: As a powerful tool for managing side effects, useEffect comes with some best practices that can help you write efficient and optimized code. Let’s dive into these best practices in detail:</p><ol><li>Use useEffect for Side Effects: useEffect is designed for handling side effects, such as fetching data, updating the DOM, or subscribing to events. Avoid using it for other purposes like changing component state, as this can lead to unnecessary re-renders and performance issues.</li><li>Specify Dependencies to Prevent Unnecessary Re-renders: Specify dependencies in the second argument of useEffect, which is an array of values that the effect depends on. This helps prevent unnecessary re-renders by ensuring that the effect only runs when the specified dependencies change.</li><li>Avoid Overusing useEffect: While useEffect is a powerful tool, overusing it can lead to complex and hard-to-maintain code. Use it only when necessary and avoid chaining multiple useEffect calls, as this can make your code difficult to understand and debug.</li><li>Use Cleanup Function for Unsubscribing and Cleanup: If your effect involves subscribing to an event or socket, make sure to return a cleanup function from the effect. This ensures that the cleanup logic is executed when the component unmounts or when the effect dependencies change.</li><li>Avoid Using Anonymous Functions as Dependencies: Avoid using anonymous functions as dependencies in useEffect, as they can cause the effect to run on every render. Instead, use useCallback or useMemo to memoize the function and prevent unnecessary re-renders.</li><li>Use useCallback and useMemo for Optimizations: If your effect involves passing a callback function as a prop to child components, use useCallback to memoize the function and prevent unnecessary re-renders. Similarly, use useMemo to memoize expensive calculations and prevent them from re-computing on every render.</li></ol><h3>Practical Examples of Using useEffect:</h3><p>Let’s explore some practical examples of using useEffect in real-world scenarios:</p><h4>Fetching Data from an API:</h4><p>useEffect can be used to fetch data from an API and update the component state. You can use the useEffect callback to make the API call and handle the response, and specify the dependencies to prevent unnecessary re-fetching.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const PostList = () =&gt; {<br>  const [posts, setPosts] = useState([]);<br><br>  useEffect(() =&gt; {<br>    const fetchPosts = async () =&gt; {<br>      try {<br>        const response = await fetch(<br>          &quot;https://jsonplaceholder.typicode.com/posts&quot;<br>        );<br>        const data = await response.json();<br>        setPosts(data);<br>      } catch (error) {<br>        console.error(&quot;Failed to fetch posts:&quot;, error);<br>      }<br>    };<br>    fetchPosts();<br>  }, []);<br><br>  return (<br>    &lt;ul&gt;<br>      {posts.map((post) =&gt; (<br>        &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default PostList;</pre><h4>Subscribing to an Event or Socket:</h4><p>useEffect can also be used to subscribe to an event or socket, and clean up the subscription when the component unmounts. You can use the useEffect callback to subscribe to the event or socket, and return a cleanup function to unsubscribe.</p><pre>import React, { useEffect } from &quot;react&quot;;<br><br>const EventSubscriber = () =&gt; {<br>  useEffect(() =&gt; {<br>    const socket = new WebSocket(&quot;wss://api.example.com/socket&quot;);<br><br>    socket.addEventListener(&quot;message&quot;, handleSocketMessage);<br><br>    return () =&gt; {<br>      socket.removeEventListener(&quot;message&quot;, handleSocketMessage);<br>      socket.close();<br>    };<br>  }, []); // Empty dependency array to run effect only on mount<br><br>  const handleSocketMessage = (event) =&gt; {<br>    // Handle socket message<br>  };<br><br>  return &lt;div&gt;{/* Render subscribed data */}&lt;/div&gt;;<br>};</pre><h4>Managing Document Title and Browser Events:</h4><p>useEffect can be used to manage the document title and add event listeners to the window or document. You can use the useEffect callback to update the document title and add event listeners, and return a cleanup function to remove the event listeners.</p><pre>import React, { useEffect } from &quot;react&quot;;<br><br>const DocumentManager = () =&gt; {<br>  useEffect(() =&gt; {<br>    document.title = &quot;My App&quot;; // Update document title<br><br>    window.addEventListener(&quot;scroll&quot;, handleScroll); // Add event listener<br><br>    return () =&gt; {<br>      window.removeEventListener(&quot;scroll&quot;, handleScroll); // Remove event listener<br>    };<br>  }, []); // Empty dependency array to run effect only on mount<br><br>  const handleScroll = () =&gt; {<br>    // Handle scroll event<br>  };<br><br>  return &lt;div&gt;{/* Render component content */}&lt;/div&gt;;<br>};</pre><p>Common Mistakes and Pitfalls to Avoid: As you work with useEffect, be aware of some common mistakes and pitfalls that can affect the performance and maintainability of your code. Here are a few to keep in mind:</p><ol><li>Not specifying dependencies: Omitting the dependency array in useEffect can lead to unexpected behavior, as the effect may run on every render. Always specify the dependencies to ensure that the effect only runs when the specified dependencies change.</li><li>Overusing useEffect: Using useEffect excessively can lead to complex and difficult-to-maintain code. Be mindful of using it only when necessary, and avoid chaining multiple useEffect calls in a single component.</li><li>Using anonymous functions as dependencies: Using anonymous functions as dependencies can cause the effect to run on every render, leading to performance issues. Instead, use useCallback or useMemo to memoize functions and prevent unnecessary re-renders.</li></ol><h3>Conclusion:</h3><p>In conclusion, mastering React Hooks useEffect is crucial for efficient state management and handling side effects in your functional components. By following the best practices outlined in this blog post, you can optimize your code for performance, maintainability, and scalability. Remember to use useEffect only when necessary, specify dependencies, and use cleanup functions for unsubscribing and cleanup. By avoiding common mistakes and pitfalls, you can make the most out of this powerful React feature and build robust and performant applications.</p><p>If you have any further questions or want to connect, feel free to check out my LinkedIn profile <a href="https://www.linkedin.com/in/joaopaulomarra/">João Paulo Marra</a>!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3cf64710c15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step React Hooks Tutorial for Beginners: A Comprehensive Guide]]></title>
            <link>https://medium.com/@joaopaulocmarra/step-by-step-react-hooks-tutorial-for-beginners-a-comprehensive-guide-c0fbafd1b3e1?source=rss-a4eaccf640d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0fbafd1b3e1</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Joao Paulo C. Marra]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 14:07:01 GMT</pubDate>
            <atom:updated>2023-04-17T14:07:01.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuoxJo0ErQ6P-_eT7_SLBw.png" /></figure><h3>Introduction:</h3><p>Welcome to our step-by-step React Hooks tutorial for beginners! If you’re new to React and want to learn how to use Hooks, you’re in the right place. React Hooks are a powerful feature introduced in React 16.8 that allows you to manage state and side effects in functional components without needing to use class components. In this tutorial, we’ll cover the basics of React Hooks, including useState, useEffect, and useRef, and provide you with practical examples to help you understand how to use them in your own React applications. So, let’s dive in and learn how to level up your React skills with Hooks!</p><h3>Prerequisites:</h3><p>Before diving into this tutorial, you should have basic knowledge of HTML, CSS, and JavaScript. Familiarity with React concepts such as components, props, and state will also be helpful. To follow along with the code examples, you’ll need Node.js and npm (Node Package Manager) installed on your machine.</p><h3>Setting Up a React Project:</h3><p>To get started, let’s set up a new React project using Create React App, a popular tool for creating React applications. Open your terminal and run the following command:</p><pre>npx create-react-app react-hooks-tutorial</pre><p>This will create a new React project with the name “react-hooks-tutorial” in the current directory. Once the project is created, navigate to the project directory by running:</p><pre>cd react-hooks-tutorial</pre><p>Now, you’re ready to start exploring React Hooks!</p><p>Understanding useState Hook: The useState Hook is used to manage state in functional components. It allows you to declare state variables in your functional components and provides functions to update the state and trigger a re-render of the component. Let’s see how it works with some examples.</p><h3>Initializing State with useState:</h3><p>To initialize state in a functional component, you can use the <a href="https://react.dev/reference/react/useState">useState</a> Hook by importing it from the ‘react’ library. Here’s an example:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount(count - 1)}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Counter;</pre><p>In the example above, we’re using the useState Hook to declare a state variable called “count” and a function called “setCount” to update the state. We’re initializing the state with a value of 0, and displaying the current value of “count” in the component’s UI. When the “Increment” or “Decrement” buttons are clicked, the “setCount” function is called with the updated value of “count”, triggering a re-render of the component.</p><h3>Updating State with useState:</h3><p>You can update state in a functional component using the functions provided by the useState Hook. Here’s an example:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const Form = () =&gt; {<br>  const [name, setName] = useState(&quot;&quot;);<br>  const [email, setEmail] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;form&gt;<br>      &lt;label&gt;<br>        Name:{&quot; &quot;}<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={name}<br>          onChange={(e) =&gt; setName(e.target.value)}<br>        /&gt;<br>      &lt;/label&gt;<br>      &lt;label&gt;<br>        Email:{&quot; &quot;}<br>        &lt;input<br>          type=&quot;email&quot;<br>          value={email}<br>          onChange={(e) =&gt; setEmail(e.target.value)}<br>        /&gt;<br>      &lt;/label&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default Form;</pre><p>In this example, we’re using two separate state variables, “name” and “email”, to manage the input values of a form. We’re using the “setName” and “setEmail” functions provided by the useState Hook to update the state whenever the input values change. This allows us to capture the user’s input and use it in our form submission logic.</p><h3>Using Multiple State Variables with useState:</h3><p>You can use the useState Hook multiple times in a single component to manage multiple pieces of state independently. Here’s an example:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const TodoList = () =&gt; {<br>  const [todos, setTodos] = useState([]);<br>  const [newTodo, setNewTodo] = useState(&quot;&quot;);<br><br>  const addTodo = () =&gt; {<br>    if (newTodo !== &quot;&quot;) {<br>      setTodos([...todos, newTodo]);<br>      setNewTodo(&quot;&quot;);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ul&gt;<br>        {todos.map((todo, index) =&gt; (<br>          &lt;li key={index}&gt;{todo}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={newTodo}<br>        onChange={(e) =&gt; setNewTodo(e.target.value)}<br>      /&gt;<br>      &lt;button onClick={addTodo}&gt;Add Todo&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default TodoList;</pre><p>In this example, we’re using two separate state variables, “todos” and “newTodo”, to manage a list of todos and the input value for adding a new todo. We’re using the “setTodos” and “setNewTodo” functions provided by the useState Hook to update the state accordingly.</p><h3>Managing Side Effects with useEffect Hook:</h3><p>The <a href="https://react.dev/reference/react/useEffect">useEffect</a> Hook is used to manage side effects, such as fetching data, subscribing to a service, or updating the DOM, in functional components. It allows you to perform side effects after the component has rendered and handle cleanup when the component is unmounted or when dependencies change. Let’s see how it works with some examples.</p><h3>Fetching Data with useEffect:</h3><p>Fetching data is a common side effect in web applications. You can use the useEffect Hook to fetch data from an API and update the component’s state accordingly. Here’s an example:</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const PostList = () =&gt; {<br>  const [posts, setPosts] = useState([]);<br><br>  useEffect(() =&gt; {<br>    const fetchPosts = async () =&gt; {<br>      try {<br>        const response = await fetch(<br>          &quot;https://jsonplaceholder.typicode.com/posts&quot;<br>        );<br>        const data = await response.json();<br>        setPosts(data);<br>      } catch (error) {<br>        console.error(&quot;Failed to fetch posts:&quot;, error);<br>      }<br>    };<br>    fetchPosts();<br>  }, []);<br><br>  return (<br>    &lt;ul&gt;<br>      {posts.map((post) =&gt; (<br>        &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default PostList;</pre><p>In this example, we’re using the useEffect Hook to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a> a list of posts from a <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> API. The useEffect Hook takes a callback function as its first argument, which is called after the component has rendered. We’re using an async function to fetch the data and update the state using the “setPosts” function. The empty array “[]” passed as the second argument to useEffect ensures that the effect only runs once, when the component mounts.</p><h3>Handling Cleanup with useEffect:</h3><p>Sometimes, side effects require cleanup, such as unsubscribing from a service or removing event listeners. The useEffect Hook allows you to return a cleanup function from the effect callback function. Here’s an example:</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>const Timer = () =&gt; {<br>  const [time, setTime] = useState(0);<br><br>  useEffect(() =&gt; {<br>    const timerId = setInterval(() =&gt; {<br>      setTime((prevTime) =&gt; prevTime + 1);<br>    }, 1000);<br><br>    return () =&gt; {<br>      clearInterval(timerId);<br>    };<br>  }, []);<br><br>  return &lt;div&gt;Time: {time} seconds&lt;/div&gt;;<br>};<br><br>export default Timer;</pre><p>In this example, we’re using the useEffect Hook to update the component’s state “time” every second to create a simple timer. We’re using the setInterval function to run the timer logic and returning a cleanup function that clears the interval with clearInterval when the component is unmounted or when the dependencies change.</p><h3>Conclusion:</h3><p><a href="https://react.dev/reference/react">React Hooks</a> are a powerful feature in React that allows you to manage state and side effects in functional components. They provide a more concise and flexible way to handle state and side effects compared to class components. In this tutorial, we covered the basics of React Hooks, including useState for managing state, useEffect for managing side effects, and how to use them in your React applications. We also discussed best practices for SEO, such as incorporating keywords in your content, optimizing your headings and meta tags, and providing high-quality, unique, and original content. By following these best practices, you can improve the visibility of your blog post in search engine results and attract more organic traffic.</p><p>If you have any further questions or want to connect, feel free to check out my LinkedIn profile <a href="https://www.linkedin.com/in/joaopaulomarra/">João Paulo Marra</a>!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0fbafd1b3e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>