<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dan Mugisho M.</title>
    <description>The latest articles on DEV Community by Dan Mugisho M. (@danmugh).</description>
    <link>https://dev.to/danmugh</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F838471%2F9f045fc0-3a53-4fbc-9a4d-9d0f91cb9ee1.jpg</url>
      <title>DEV Community: Dan Mugisho M.</title>
      <link>https://dev.to/danmugh</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/danmugh"/>
    <language>en</language>
    <item>
      <title>Understand Open Graph ( OG ) in Next Js : A Practical Guide</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Thu, 31 Oct 2024 18:46:55 +0000</pubDate>
      <link>https://dev.to/danmugh/understand-open-graph-og-in-next-js-a-practical-guide-3ade</link>
      <guid>https://dev.to/danmugh/understand-open-graph-og-in-next-js-a-practical-guide-3ade</guid>
      <description>&lt;p&gt;Imagine a world where your content effortlessly shares itself, captivating audiences on social media. This is the reality made possible by Open Graph (OG) protocol. In the realm of Next.js, the use of OG becomes even more strategic.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzs14s9umtwdf5votpxyu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzs14s9umtwdf5votpxyu.png" alt="Open Graph Preview on social media platforms" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Open Graph&lt;/strong&gt; is a protocol that allows websites to provide rich snippets of information about their content when shared on social media platforms. By implementing Open Graph image, you can control how your content appears when shared on Facebook, Twitter, LinkedIn, and other platforms. This ensures that your posts are visually appealing and informative, encouraging users to click and engage with your content.&lt;/p&gt;

&lt;p&gt;In this guide, we’ll explore how to generate OG images dynamically and cover different implementation scenarios, tailoring OG tags to match your specific content requirements. Ensuring your content looks great when shared on social media platforms.&lt;/p&gt;

&lt;p&gt;Assuming you have a solid understanding of Next.js and its core concepts, and familiarity with Tailwind CSS for styling Open Graph, Let’s start by :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creating a Next Js project &lt;strong&gt;npx create-next-app@latest&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Installing &lt;a href="https://chromewebstore.google.com/detail/ograph-previewer/ggcfeakcnodgcmmllfdbmngekljbhiim" rel="noopener noreferrer"&gt;OGraph Previewer&lt;/a&gt; Chrome extension, a must-have tool when working with Open Graph (OG). It offers a quick and easy way to visualize how your web pages will appear when shared on social media platforms. Simply install the extension and visit any page on your website. With a single click, you’ll be able to see a preview of your page’s title, description, and image, ensuring that they align with your desired presentation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before we delve into the intricacies of Open Graph tags in Next.js, let’s set the stage with a clean and well-structured project.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Remove the app/fonts files since we won’t be needed them for our blog setup.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Update app/layout.tsx to :&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./globals.css";

import type { Metadata } from "next";
import { Poppins } from "next/font/google";

const poppins = Poppins({
  subsets: ["latin"],
  display: "swap",
  weight: ["300", "400", "500", "600", "700"],
  variable: "--poppins",
});

const baseUrl = "https://www.danmugh.com/"; // Your website url

export async function generateMetadata(): Promise&amp;lt;Metadata&amp;gt; {
  const title = "My Blog";

  const description =
    "Welcome to my blog! Dive into a wealth of insightful articles, practical guides, and project breakdowns, empowering you to level up your Rust and Blockchain development skills.";

  return {
    metadataBase: new URL(baseUrl),
    title,
    description,
    themeColor: "black"
  };
}

export default function RootLayout({
  children,
}: Readonly&amp;lt;{
  children: React.ReactNode;
}&amp;gt;) {
  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;body
        className={`${poppins.className} ${poppins.variable} font-sans bg-dark`}
      &amp;gt;
        &amp;lt;div className="w-full min-h-screen flex flex-col sm:px-[100px] md:px-[140px] lg:px-[200px] xl:px-[225px]"&amp;gt;
          {children}
        &amp;lt;/div&amp;gt;
      &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Update app/page.tsx to :
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

export default function Home() {
  return (
    &amp;lt;div className="w-full min-h-screen pt-24 "&amp;gt;
      &amp;lt;div className="flex flex-col justify-center items-center"&amp;gt;
        &amp;lt;h1 className="text-white text-3xl sm:text-5xl text-center font-semibold"&amp;gt;
          Blog Page
        &amp;lt;/h1&amp;gt;

        &amp;lt;p className="w-[70%] mt-8 mb-3 text-lg text-white/50 text-center font-medium leading-normal"&amp;gt;
          Welcome to my blog! Dive into a wealth of insightful articles,
          practical guides, and project breakdowns, empowering you to level up
          your Rust and Blockchain development skills.
        &amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Delete all the files in public directory.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create in src, components and lib directories&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In src/lib, create Resources.ts file&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create in src, app/api/og directory&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create in public, fonts directory and add &lt;a href="https://fonts.google.com/specimen/Rubik" rel="noopener noreferrer"&gt;rubik.ttf&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We should have this structure :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.
├── public
│   └── fonts
│       └── rubik.ttf
├── src
│   ├── app
│   │   ├── api
│   │   │   └── og
│   │   │        └── route.tsx
│   │   ├── favicon.ico
│   │   ├── globals.css
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── components
│   └── lib
│       └── Resources.ts 
│
├── tailwind.config.ts
├── tsconfig.json
├── README.md
├── next-env.d.ts
├── next.config.mjs
├── package.json
└── postcss.config.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we’ve set up a basic blog structure in place, we’re ready to add content and implement Open Graph image.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Implementing Open Graph using an Image file.
&lt;/h2&gt;

&lt;p&gt;Let’s add this image in public directory, and export it in &lt;strong&gt;src/lib/Resources.ts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5arkajf1kudlcs11sjr9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5arkajf1kudlcs11sjr9.png" alt="OG Image" width="800" height="420"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Thumbnail = '/thumbnail.png'; // Assuming the image name is thumbnail
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Change the layout metadata to :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export async function generateMetadata(): Promise&amp;lt;Metadata&amp;gt; {
  const title = "My Blog";

  const description =
    "Welcome to my blog! Dive into a wealth of insightful articles, practical guides, and project breakdowns, empowering you to level up your Rust and Blockchain development skills.";

  return {
    metadataBase: new URL(baseUrl),
    title,
    description,
    themeColor: "black",
    openGraph: {
      title,
      description,
      url: baseUrl,
      images: [
        {
          url: Thumbnail,
          secureUrl: Thumbnail,
          width: 1200,
          height: 630,
          alt: "Preview image for Dan Mugh's Blog",
        },
      ],
      type: "website",
      siteName: "Dan Mugh's Blog",
    },
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;const title and description :&lt;/strong&gt; Respectively set the title and the description of the blog page and the Open Graph title &amp;amp; description.&lt;br&gt;
&lt;strong&gt;metadataBase :&lt;/strong&gt; Specifies the base URL of the website ( &lt;a href="https://www.danmugh.com" rel="noopener noreferrer"&gt;https://www.danmugh.com&lt;/a&gt; in our case ).&lt;br&gt;
&lt;strong&gt;themeColor :&lt;/strong&gt; The preferred color for the browser’s UI.&lt;br&gt;
&lt;strong&gt;openGraph&lt;/strong&gt; is an object containing Open Graph metadata :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;title and description: These repeat the title and description from the outer level, ensuring consistency.&lt;/li&gt;
&lt;li&gt;url: This property sets the URL of the current page. &lt;/li&gt;
&lt;li&gt;images is an array of image objects for the Open Graph :&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;url: The URL of the image.&lt;/li&gt;
&lt;li&gt;secureUrl: The secure URL of the image (e.g., HTTPS).&lt;/li&gt;
&lt;li&gt;width and height: These properties provide the dimensions of the image.&lt;/li&gt;
&lt;li&gt;alt: The alternative text for the image.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;type: Specifies the type of content on your page. Common values include “website”, “article”, “book”, and “profile”.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;siteName: The name of the website.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note that the flexibility of having multiple image objects in images array, is particularly useful for catering to different social media platforms and their specific image size requirements. For example, Twitter might prefer a smaller square image (800x800), while Facebook might favor a larger landscape format (1800x1600). By including multiple image objects with appropriate dimensions, you ensure that your content is displayed optimally on various platforms, maximizing its visual impact and potential reach.&lt;/p&gt;

&lt;p&gt;After adding these changes, we should be able to test from OGraph Previewer and get this output&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj3g22td9u6p9lkyr6gqe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj3g22td9u6p9lkyr6gqe.png" alt="Image Preview" width="800" height="807"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And having the following meta tags as output :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;meta property="og:title" content="My Blog" /&amp;gt; 
&amp;lt;meta property="og:description" content="Dive into a wealth of insightful articles..." /&amp;gt; 
&amp;lt;meta property="og:url" content="https://www.danmugh.com/" /&amp;gt; 
&amp;lt;meta property="og:site_name" content="Dan Mugh's Blog" /&amp;gt;
&amp;lt;meta property="og:locale" content="en_US" /&amp;gt;
&amp;lt;meta property="og:image" content="http://localhost:3000/thumbnail.png"&amp;gt; 
&amp;lt;meta property="og:image:alt" content="Preview image for Dan Mugh's Blog" /&amp;gt; 
&amp;lt;meta property="og:image:type" content="image/png" /&amp;gt;
&amp;lt;meta property="og:image:width" content="1200" /&amp;gt;
&amp;lt;meta property="og:image:height" content="630" /&amp;gt;
&amp;lt;meta property="og:type" content="website" /&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Implementing Open Graph using a generated Image.
&lt;/h2&gt;

&lt;p&gt;The easiest way to generate an image is to use the &lt;a href="https://nextjs.org/docs/app/api-reference/functions/image-response" rel="noopener noreferrer"&gt;ImageResponse&lt;/a&gt; API from next/og.&lt;/p&gt;

&lt;p&gt;Let’s create route.tsx in app/api/og and add the below code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ImageResponse } from "next/og";

// Route segment config
export const runtime = "edge";

export const contentType = "image/png";

// Image generation
export async function GET() {
  try {
    // Font
    const rubik = await fetch(
      new URL("../../../../public/fonts/rubik.ttf", import.meta.url)
    ).then((res) =&amp;gt; res.arrayBuffer());

    return new ImageResponse(
      (
        &amp;lt;div
          style={{
            fontFamily: "Rubik",
            fontWeight: "bolder",
            background: "linear-gradient(to right, #6a11cb 0%, #2575fc 100%)",
          }}
          tw="w-full h-full p-8 flex items-center justify-center relative"
        &amp;gt;
          &amp;lt;div tw="flex flex-col"&amp;gt;
            &amp;lt;h1 tw="text-white text-5xl font-bold leading-[4px]"&amp;gt;Learn more today!&amp;lt;/h1&amp;gt;
            &amp;lt;h1 tw="text-white/70 text-3xl font-bold leading-[8px]"&amp;gt;Dive into the future of tech...&amp;lt;/h1&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      ),
      {
        fonts: [
          {
            name: "Rubik",
            data: rubik,
            weight: 700,
            style: "normal",
          },
        ],
      }
    );
  } catch (e: any) {
    return new Response("Failed to generate OG Image", { status: 500 });
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;runtime Property :&lt;/strong&gt; This property specifies that the code should be executed on the edge, which is a serverless environment optimized for serving static content&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;alt, size, and contentType Properties :&lt;/strong&gt; These properties define the alternative text, dimensions, and content type of the image, respectively. You can set the size and alt from the openGraph in the layout file as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GET Function :&lt;/strong&gt; This function handles HTTP GET requests to the route.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Font Loading :&lt;/strong&gt; The code fetches the rubik.ttf font file and converts it to an array buffer. This is necessary for including the font in the image generation process ( You may need to adjust the font path and file name (rubik.ttf) to match your project structure ).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Image Creation :&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A new ImageResponse is created, which represents the generated image.&lt;/li&gt;
&lt;li&gt;The div element inside the ImageResponse defines the content of the image. It includes a heading with the blog title and a background gradient.&lt;/li&gt;
&lt;li&gt;The fonts property specifies the font used in the image. The rubik font data is included in the data property.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Error Handling :&lt;/strong&gt; A try-catch block is used to handle potential errors during the font fetching and image generation process. If an error occurs, a response with a 500 status code is returned.&lt;/p&gt;

&lt;p&gt;You can effectively combine Tailwind CSS classes with custom CSS for a more flexible approach. And I will recommend to use Tailwind classes ( tw ) for common styles and custom CSS for more specific or complex requirements.&lt;/p&gt;

&lt;p&gt;Additionally, we can update layout openGraph to :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;…
openGraph: {
      title,
      description,
      url: baseUrl,
      images: [
        {
          url: `/api/og`,
          width: 1200,
          height: 630,
          alt: "Preview image for Dan Mugh's Blog",
        },
      ],
      locale: "en_US",
      type: "website",
      siteName: "Dan Mugh's Blog",
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By now, we should be able to see the output in the OGraph Previewer, or by visiting &lt;a href="http://localhost:3000/api/og" rel="noopener noreferrer"&gt;http://localhost:3000/api/og&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyezwqwg2q9troo6tps90.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyezwqwg2q9troo6tps90.png" alt="Image Preview" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And have this output :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;meta property="og:title" content="My Blog"&amp;gt;
&amp;lt;meta property="og:description" content="Dive into a wealth of insightful articles, practical guides, and project breakdowns, empowering you to level up your Rust and Blockchain development skills."&amp;gt;
&amp;lt;meta property="og:url" content="https://www.danmugh.com"&amp;gt;
&amp;lt;meta property="og:site_name" content="Dan Mugh's Blog"&amp;gt;
&amp;lt;meta property="og:locale" content="en_US"&amp;gt;
&amp;lt;meta property="og:image" content="http://localhost:3000/api/og"&amp;gt;
&amp;lt;meta property="og:image:width" content="1200"&amp;gt;
&amp;lt;meta property="og:image:height" content="630"&amp;gt;
&amp;lt;meta property="og:image:alt" content="Preview image for Dan Mugh's Blog"&amp;gt;
&amp;lt;meta property="og:type" content="website"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While we’ve covered core concepts for creating Open Graph image, you can explore &lt;a href="https://og-playground.vercel.app/" rel="noopener noreferrer"&gt;Vercel Image Playground&lt;/a&gt; for interactive experimentation. This handy tool lets you visually build and test Open Graph images by directly editing the HTML and CSS that define their appearance. You can play with fonts, colors, layouts, and even preview the generated image in real-time.&lt;/p&gt;

&lt;p&gt;Once you’ve mastered the basics here, head over to the Vercel Image Playground to solidify your Open Graph image creation skills!&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Implement Dynamic Open Graph Route.
&lt;/h2&gt;

&lt;p&gt;To make our blog truly dynamic and showcase fresh content, we need to integrate an API to fetch articles. Here, we’ll leverage the dev.to API, which provides access to published articles on the platform. The API endpoint we’ll use is :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;https://dev.to/api/articles/{username}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don’t have a dev.to account yet, no worries! You can simply use mine (danmugh) for demonstration purposes. ( But make sure to replace it with your username later when you create your own account 😄 ).&lt;/p&gt;

&lt;p&gt;I’ve made some significant changes to the project, to fetch and display blog articles. I won’t delve into the details here. Feel free to clone &lt;a href="https://github.com/danmugh/nextjs-opengraph-blog/tree/imporve-blog-features" rel="noopener noreferrer"&gt;the repository&lt;/a&gt; and update your project to incorporate these enhancements.&lt;/p&gt;

&lt;p&gt;Assuming you’ve successfully updated the project and you’re seeing the blog content locally, let’s go to &lt;strong&gt;article/[slug]&lt;/strong&gt; and change the metadata to :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export async function generateMetadata({
  params: { slug },
}: Props): Promise&amp;lt;Metadata&amp;gt; {
  const baseUrl = "https://www.danmugh.com/";

  const article = (await serverServices.getArticle(
    slug
  )) as IArticleModel;

  const title = article.title;
  const description = article.description;
  const articleSlug = article.slug;

  return {
    title,
    description,
    metadataBase: new URL(baseUrl),
    openGraph: {
      title,
      description,
      images: [
        {
          url: `/api/og?title=${articleSlug}`,
          width: 1200,
          height: 630,
          alt: `Preview image for ${title}`,
        },
      ],
      type: "article",
      url: `/blog/${slug}`,
    },
    alternates: {
      canonical: `/blog/${slug}`,
    },
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are passing the article slug to the Open Graph image, so we can fetch the article data from the route.&lt;/p&gt;

&lt;p&gt;In &lt;strong&gt;api/og/route.tsx&lt;/strong&gt;, above font loading, we can add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
const article: IArticleModel = await fetch(
      `https://dev.to/api/articles/danmugh/${req.nextUrl.searchParams.get(
        "title"
      )}`
    ).then((res) =&amp;gt; res.json());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have the article data in the route, we can use the data to design the Open Graph Image.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
return new ImageResponse(
      (
        &amp;lt;div
          style={{
            fontFamily: "Rubik",
            fontWeight: "bolder",
            background: "linear-gradient(to right, #6a11cb 0%, #2575fc 100%)",
          }}
          tw="w-full h-full p-8 flex items-center justify-center relative"
        &amp;gt;
          &amp;lt;div tw="w-full flex flex-col"&amp;gt;
            &amp;lt;h1 tw="text-[36px] text-white font-bold"&amp;gt;{article.title}&amp;lt;/h1&amp;gt;
            &amp;lt;div tw="h-[50px] mt-3 flex justify-between items-center"&amp;gt;
              &amp;lt;div tw="flex justify-center items-center"&amp;gt;
                &amp;lt;img
                  src={article.user.profile_image}
                  width={100}
                  height={100}
                  alt={article.title}
                  tw="w-[60px] h-[60px] rounded-[10px] mr-2"
                  style={{ objectFit: "cover" }}
                /&amp;gt;
                &amp;lt;div tw="flex flex-col"&amp;gt;
                  &amp;lt;p tw="text-[20px] text-white font-semibold leading-[1px]"&amp;gt;
                    {article.user.name}
                  &amp;lt;/p&amp;gt;
                  &amp;lt;p tw="text-[20px] text-white/60 font-semibold leading-[1px]"&amp;gt;
                    Author
                  &amp;lt;/p&amp;gt;
                &amp;lt;/div&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;p tw="text-[20px] text-white font-semibold"&amp;gt;
                {article.reading_time_minutes} Min read
              &amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      ),
      {
        fonts: [
          {
            name: "Rubik",
            data: rubik,
            weight: 700,
            style: "normal",
          },
        ],
      }
   );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We should have a preview of the OG image from the OGraph Previewer extension.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5amifgl7mwp9c3tshk4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5amifgl7mwp9c3tshk4.png" alt="Image description" width="800" height="816"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Or by visiting &lt;a href="http://localhost:3000/api/og?title=$%7BarticleSlug%7D" rel="noopener noreferrer"&gt;http://localhost:3000/api/og?title=${articleSlug}&lt;/a&gt; ( Assuming the articleSlug is “integrating-wagmi-v2-and-rainbowkit-in-nextjs-a-comprehensive-guide-part-1–37ck” )&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcj9v4wo3rwl7d95khfzz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcj9v4wo3rwl7d95khfzz.png" alt="Image Preview" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And this output as well :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;meta property="og:title" content="Integrating Wagmi V2 and Rainbowkit in NextJs : A Comprehensive Guide (Part 1)"&amp;gt;
&amp;lt;meta property="og:description" content="Welcome to the forefront of Web3/Frontend development, where we embark on a transformative journey of..."&amp;gt;
&amp;lt;meta property="og:url" content="https://www.danmugh.com/blog/integrating-wagmi-v2-and-rainbowkit-in-nextjs-a-comprehensive-guide-part-1-37ck"&amp;gt;
&amp;lt;meta property="og:image" content="http://localhost:3000/api/og?title=integrating-wagmi-v2-and-rainbowkit-in-nextjs-a-comprehensive-guide-part-1-37ck"&amp;gt;
&amp;lt;meta property="og:image:width" content="1200"&amp;gt;
&amp;lt;meta property="og:image:height" content="630"&amp;gt;
&amp;lt;meta property="og:image:alt" content="Preview image for Integrating Wagmi V2 and Rainbowkit in NextJs : A Comprehensive Guide (Part 1)"&amp;gt;
&amp;lt;meta property="og:type" content="article"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we’ve explored various Open Graph implementation scenarios, let’s wrap up this guide with a more intricate case ( a truly mind-bending case study ), where we’ll push the boundaries of Open Graph image customization to the absolute limit. Buckle up, folks 😎&lt;/p&gt;

&lt;p&gt;In this section, we’ll delve into advanced techniques for customizing OG images, allowing you to create truly unique and visually striking previews for your content.&lt;/p&gt;

&lt;p&gt;Let’s add this image in &lt;strong&gt;public&lt;/strong&gt; and export it from &lt;strong&gt;lib/Resource.ts&lt;/strong&gt;. We shall use it as background of the OG image we are going to build.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6u5ezvwhrmp8u4ziwkwf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6u5ezvwhrmp8u4ziwkwf.png" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const OGBackground = '/OGBackground.png'; // Assuming the image name is OGBackground
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;strong&gt;route.tsx&lt;/strong&gt;, we can fetch the background image file and passe it as an ArrayBuffer :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bg = await fetch(
      new URL("../../../../public/OGBackground.png", import.meta.url)
  ).then((res) =&amp;gt; res.arrayBuffer());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And change the &lt;strong&gt;ImageResponse&lt;/strong&gt; to :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div
   style={{
     fontFamily: "Rubik",
     fontWeight: "bolder",
   }}
   tw="w-full h-full flex items-center justify-center relative"
&amp;gt;
   &amp;lt;img
      src={bg}
      width={100}
      height={100}
      alt="background"
      tw="w-full h-full"
      style={{ objectFit: "cover" }}
    /&amp;gt;
    &amp;lt;div tw="absolute top-0 left-0 p-16 w-full h-full flex items-center justify-start"&amp;gt;
      &amp;lt;div
        style={{ background: "#1B2022" }}
        tw="max-w-[420px] h-full mx-0 p-5 shadow-[0px_8px_16px_0px_rgba(0,0,0,0.15)] rounded-xl flex flex-col items-start justify-between"
      &amp;gt;
        &amp;lt;div tw="flex flex-col"&amp;gt;
           &amp;lt;div tw="flex justify-center items-center"&amp;gt;
              &amp;lt;img
                 src={article.cover_image}
                 tw="w-full h-[190px]"
                 width={100}
                 height={100}
              /&amp;gt;
              &amp;lt;/div&amp;gt;
                 &amp;lt;h2 tw="mt-4 text-2xl text-white text-start font-bold leading-8 line-clamp-3"&amp;gt;
                   {article.title}
                 &amp;lt;/h2&amp;gt;
                 &amp;lt;p tw="text-lg text-white/50 text-start font-normal leading-6 line-clamp-5"&amp;gt;
                   {article.description}
                 &amp;lt;/p&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div tw="w-full flex justify-between items-center"&amp;gt;
                 &amp;lt;p tw="text-[17px] text-white/75 font-semibold"&amp;gt;
                   {article.readable_publish_date}
                 &amp;lt;/p&amp;gt;
                 &amp;lt;p tw="text-[17px] text-white/75 font-semibold"&amp;gt;
                   {article.reading_time_minutes} Min read
                 &amp;lt;/p&amp;gt;
              &amp;lt;/div&amp;gt;
         &amp;lt;/div&amp;gt;
     &amp;lt;/div&amp;gt;
     &amp;lt;div tw="absolute top-0 right-0 p-16 w-full h-full flex items-end justify-end"&amp;gt;
         &amp;lt;div tw="flex justify-center items-center"&amp;gt;
              &amp;lt;p tw="text-[22px] text-white/85 font-semibold leading-[1px]"&amp;gt;
                  #LearnMoreToday
               &amp;lt;/p&amp;gt;
               &amp;lt;img
                 src={article.user.profile_image}
                 width={100}
                 height={100}
                 alt={article.title}
                 tw="w-[40px] h-[40px] rounded-[10px] ml-3"
                 style={{ objectFit: "cover" }}
               /&amp;gt;
         &amp;lt;/div&amp;gt;
     &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By combining Tailwind CSS classes with custom CSS, we have created a highly customized, unique and visually appealing OG Image.&lt;/p&gt;

&lt;p&gt;And here we are 😎&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxeydzj6yidb69n9yurrv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxeydzj6yidb69n9yurrv.png" alt="Image preview" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In this guide, we’ve explored the essential concepts of Open Graph metadata in Next.js. By understanding and implementing Open Graph, you can significantly enhance your website’s visibility and engagement on social media platforms.&lt;br&gt;
From basic setup to advanced customization, we’ve covered various techniques to create compelling and informative social media previews.&lt;br&gt;
Remember, well-crafted Open Graph metadata is an investment in your website’s online presence.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that you’ve acquired some Open Graph skills, it’s time to unleash your creativities. I’d be delighted to see the visually appealing Open Graph Images you create!&lt;/p&gt;

&lt;p&gt;Feel free to share your website links with me at &lt;a href="mailto:contact@danmugh.com"&gt;contact@danmugh.com&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;☞ &lt;a href="https://github.com/danmugh/nextjs-opengraph-blog" rel="noopener noreferrer"&gt;GitHub repo&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>seo</category>
      <category>frontend</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>Integrating Wagmi V2 and Rainbowkit in NextJs : A Comprehensive Guide (Part 1)</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Mon, 22 Apr 2024 13:32:06 +0000</pubDate>
      <link>https://dev.to/danmugh/integrating-wagmi-v2-and-rainbowkit-in-nextjs-a-comprehensive-guide-part-1-37ck</link>
      <guid>https://dev.to/danmugh/integrating-wagmi-v2-and-rainbowkit-in-nextjs-a-comprehensive-guide-part-1-37ck</guid>
      <description>&lt;p&gt;Welcome to the forefront of Web3/Frontend development, where we embark on a transformative journey of integrating Wagmi V2 alongside RainbowKit for seamless wallet connection and unlocking advanced features for a robust and feature-rich dApp.&lt;/p&gt;

&lt;p&gt;In this comprehensive guide, we’ll explore the complex landscape of modern web development, empowering you to effortlessly implement and optimize wallet functionalities within your NextJs project.&lt;/p&gt;

&lt;p&gt;Whether you’re transitioning from Wagmi V1 or venturing into Wagmi V2 for the first time, this article promises to equip you with the knowledge to elevate your user experiences and streamline wallet interactions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In this Part 1, we tackle the essentials: establishing seamless wallet connections and fetching crucial user data like addresses, network details, balances, ENS names…&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Create the project
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-next-app@latest my-project - typescript - eslint
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Add Wagmi to the project, install the required packages
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add wagmi viem@2.x @tanstack/react-query
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://viem.sh/"&gt;Viem&lt;/a&gt; is a TypeScript interface for Ethereum that performs blockchain operations.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://tanstack.com/query/v5"&gt;TanStack Query&lt;/a&gt; is an async state manager that handles requests, caching, and more.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Install Rainbowkit
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add  @rainbow-me/rainbowkit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s create and export a new config using createConfig, in &lt;code&gt;lib/config.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'use client';

import { http, createStorage, cookieStorage } from 'wagmi'
import { sepolia, bscTestnet, blastSepolia } from 'wagmi/chains'
import { Chain, getDefaultConfig } from '@rainbow-me/rainbowkit'

const projectId = ‘’;

const supportedChains: Chain[] = [sepolia, bscTestnet, blastSepolia];

export const config = getDefaultConfig({
   appName: 'WalletConnection‘,
   projectId,
   chains: supportedChains as any,
   ssr: true,
   storage: createStorage({
    storage: cookieStorage,
   }),
  transports: supportedChains.reduce((obj, chain) =&amp;gt; ({ ...obj, [chain.id]: http() }), {})
 });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, Wagmi is configured to use the Sepolia, BscTestnet and blastSepolia chains, wrapped in supportedChains array.&lt;/p&gt;

&lt;p&gt;Wagmi uses client-side storage for fast initial data, but this can cause issues with SSR frameworks like Next.js. Enabling the ssr property in Wagmi config fixes this by hydrating the data on the client after the initial render.&lt;/p&gt;

&lt;p&gt;Here, we use cookieStorage to store Wagmi data in browser cookies. This allows persistence across page refreshes within the same browser.&lt;/p&gt;

&lt;p&gt;The reduce function iterates through the supportedChains array. For each chain, it creates a key-value pair in the transports object ( [bscTestnet.id]: http() ). These transports handle making HTTP requests to the blockchain nodes for interactions and data retrieval.&lt;/p&gt;

&lt;p&gt;Check out the &lt;a href="https://wagmi.sh/react/api/createConfig"&gt;createConfig docs&lt;/a&gt; for more configuration options.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrap App in Context Provider and RainbowKitProvider
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Wrap the app in the WagmiProvider React Context Provider and pass the config you created earlier to the value property. Check out the &lt;a href="https://wagmi.sh/react/api/WagmiProvider"&gt;WagmiProvider docs&lt;/a&gt; to learn more about React Context in Wagmi.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In Wagmi V2, you no longer need to pass chains to &lt;code&gt;&amp;lt;RainbowKitProvider&amp;gt;&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Inside the WagmiProvider, wrap the app in a TanStack Query React Context Provider, e.g. QueryClientProvider, and pass a new QueryClient instance to the client property.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Since Next.js 14 restricts functions in Client Components and improve code organization, let’s create a dedicated component to manage the problematic data handling logic.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;app/providers.tsx&lt;/code&gt;, add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import { WagmiProvider } from "wagmi";
import { RainbowKitProvider, darkTheme } from "@rainbow-me/rainbowkit";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

import { config } from "@/lib/config";

const queryClient = new QueryClient();

type Props = {
  children: React.ReactNode;
};

export default function Providers({ children }: Props) {
  return (
    &amp;lt;WagmiProvider config={config}&amp;gt;
      &amp;lt;QueryClientProvider client={queryClient}&amp;gt;
        &amp;lt;RainbowKitProvider
          theme={darkTheme({
            accentColor: "#0E76FD",
            accentColorForeground: "white",
            borderRadius: "large",
            fontStack: "system",
            overlayBlur: "small",
          })}
        &amp;gt;
          {children}
        &amp;lt;/RainbowKitProvider&amp;gt;
      &amp;lt;/QueryClientProvider&amp;gt;
    &amp;lt;/WagmiProvider&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are marking the component &lt;code&gt;"use client"&lt;/code&gt; as it wraps libraries &lt;strong&gt;( WagmiProvider, QueryClientProvider, RainbowKitProvider )&lt;/strong&gt; that rely on browser-specific functionalities.&lt;/p&gt;

&lt;p&gt;Since it will be imported in &lt;code&gt;layout.tsx&lt;/code&gt; ( a Server Component ), marking it &lt;strong&gt;"use client"&lt;/strong&gt; ensures these libraries are only loaded and executed on the client-side (user’s browser) during hydration. This prevents unnecessary code execution on the server and improves initial page load performance.&lt;/p&gt;

&lt;p&gt;Let’s now import Providers in layout.tsx&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import "./globals.css";
import "@rainbow-me/rainbowkit/styles.css";

import { Inter } from "next/font/google";
import Providers from "./providers";

const inter = Inter({ subsets: ["latin"] });

export default function RootLayout({
  children,
}: Readonly&amp;lt;{
  children: React.ReactNode;
}&amp;gt;) {
  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;body className={inter.className}&amp;gt;
        &amp;lt;Providers&amp;gt;{children}&amp;lt;/Providers&amp;gt;
      &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To ensure Wagmi’s cookie data persists across page loads in our Next.js application, we’ll need to set up a hydration mechanism.&lt;/p&gt;

&lt;p&gt;This involves extracting the cookie from the request headers within our server component (&lt;code&gt;app/layout.tsx&lt;/code&gt;) and using cookieToInitialState to convert it into a suitable format.&lt;/p&gt;

&lt;p&gt;Finally, we’ll pass this initial state to the WagmiProvider component located in a client component (&lt;code&gt;app/providers.tsx&lt;/code&gt;) tagged with &lt;strong&gt;"use client"&lt;/strong&gt;. This process essentially &lt;strong&gt;"hydrates"&lt;/strong&gt; the cookie data on the client-side, making it accessible throughout our dApp.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;app/layout.tsx&lt;/code&gt;, let’s add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
+ import { headers } from "next/headers";

export default function RootLayout({
  children,
}: Readonly&amp;lt;{
  children: React.ReactNode;
}&amp;gt;) {
  + const cookie = headers().get("cookie");

  return (
    &amp;lt;html lang="en"&amp;gt;
      &amp;lt;body className={inter.className}&amp;gt;
        + &amp;lt;Providers cookie={cookie}&amp;gt;{children}&amp;lt;/Providers&amp;gt;
      &amp;lt;/body&amp;gt;
    &amp;lt;/html&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in &lt;code&gt;app/providers.tsx&lt;/code&gt;, add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

...
+ import { WagmiProvider, cookieToInitialState } from "wagmi";

type Props = {
  children: React.ReactNode;
  + cookie?: string | null;
};

+ export default function Providers({ children, cookie }: Props) {
  + const initialState = cookieToInitialState(config, cookie);
  return (
    + &amp;lt;WagmiProvider config={config} initialState={initialState}&amp;gt;
      ...
    &amp;lt;/WagmiProvider&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Now that everything is set up, every component inside the Wagmi and TanStack Query Providers can use Wagmi React Hooks.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;app/components/connectButton.tsx&lt;/code&gt;, let's add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import { useEffect, useRef } from "react";
import {
  useConnectModal,
  useAccountModal,
  useChainModal,
} from "@rainbow-me/rainbowkit";
import { useAccount, useDisconnect } from "wagmi";
import { emojiAvatarForAddress } from "@/lib/emojiAvatarForAddress";

export const ConnectBtn = () =&amp;gt; {
  const { isConnecting, address, isConnected, chain } = useAccount();
  const { color: backgroundColor, emoji } = emojiAvatarForAddress(
    address ?? ""
  );

  const { openConnectModal } = useConnectModal();
  const { openAccountModal } = useAccountModal();
  const { openChainModal } = useChainModal();
  const { disconnect } = useDisconnect();

  const isMounted = useRef(false);

  useEffect(() =&amp;gt; {
    isMounted.current = true;
  }, []);

  if (!isConnected) {
    return (
      &amp;lt;button
        className="btn"
        onClick={async () =&amp;gt; {
          // Disconnecting wallet first because sometimes when is connected but the user is not connected
          if (isConnected) {
            disconnect();
          }
          openConnectModal?.();
        }}
        disabled={isConnecting}
      &amp;gt;
        { isConnecting ? 'Connecting...' : 'Connect your wallet' }
      &amp;lt;/button&amp;gt;
    );
  }

  if (isConnected &amp;amp;&amp;amp; !chain) {
    return (
      &amp;lt;button className="btn" onClick={openChainModal}&amp;gt;
        Wrong network
      &amp;lt;/button&amp;gt;
    );
  }

  return (
    &amp;lt;div className="max-w-5xl w-full flex items-center justify-between"&amp;gt;
      &amp;lt;div
        className="flex justify-center items-center px-4 py-2 border border-neutral-700 bg-neutral-800/30 rounded-xl font-mono font-bold gap-x-2 cursor-pointer"
        onClick={async () =&amp;gt; openAccountModal?.()}
      &amp;gt;
        &amp;lt;div
          role="button"
          tabIndex={1}
          className="h-8 w-8 rounded-full flex items-center justify-center flex-shrink-0 overflow-hidden"
          style={{
            backgroundColor,
            boxShadow: "0px 2px 2px 0px rgba(81, 98, 255, 0.20)",
          }}
        &amp;gt;
          {emoji}
        &amp;lt;/div&amp;gt;
        &amp;lt;p&amp;gt;Account&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;button className="btn" onClick={openChainModal}&amp;gt;
        Switch Networks
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useConnectModal, useAccountModal, useChainModal :&lt;/strong&gt; Hooks from @rainbow-me/rainbowkit that trigger specific modals (popups) for connecting wallets, managing accounts, and selecting networks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useAccount, useDisconnect :&lt;/strong&gt; Hooks from wagmi that provide information about the connected account and a function to disconnect the wallet.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;emojiAvatarForAddress :&lt;/strong&gt; A custom function (likely located in lib/emojiAvatarForAddress.js, that you will find in this project repo) generates an emoji avatar based on the connected wallet address.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This component effectively manages the user’s wallet connection experience in our Next.js dApp by leveraging RainbowKit hooks and custom functions, providing a seamless flow for connecting, switching networks, and accessing account information.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;app/components/profile.tsx&lt;/code&gt;, add :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import { useAccount, useBalance, useEnsName } from "wagmi";
import { middleEllipsis } from "@/lib/utils";
import { formatUnits } from "viem";

export default function Profile() {
  const { address, chain } = useAccount();

  const { data } = useBalance({
    address,
  });

  const ens = useEnsName({
    address,
  });

  return (
    &amp;lt;div className="mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-4 lg:text-left"&amp;gt;
      &amp;lt;div className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"&amp;gt;
        &amp;lt;h2 className="mb-3 text-2xl font-semibold"&amp;gt;Wallet address&amp;lt;/h2&amp;gt;
        &amp;lt;p className="m-0 w-[30ch] text-sm opacity-50"&amp;gt;
          {middleEllipsis(address as string, 12) || ""}
        &amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;div className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"&amp;gt;
        &amp;lt;h2 className={`mb-3 text-2xl font-semibold`}&amp;gt;Network&amp;lt;/h2&amp;gt;
        &amp;lt;p className={`m-0 max-w-[30ch] text-sm opacity-50`}&amp;gt;
          {chain?.name || ""}
        &amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;div className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"&amp;gt;
        &amp;lt;h2 className={`mb-3 text-2xl font-semibold`}&amp;gt;Balance&amp;lt;/h2&amp;gt;
        &amp;lt;div className={`m-0 max-w-[30ch] text-sm opacity-50`}&amp;gt;
          {data ? (
            &amp;lt;p&amp;gt;
              {Number(formatUnits(data.value, data.decimals)).toFixed(4)}{" "}
              {data.symbol}
            &amp;lt;/p&amp;gt;
          ) : (
            &amp;lt;div /&amp;gt;
          )}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;div className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"&amp;gt;
        &amp;lt;h2 className={`mb-3 text-2xl font-semibold`}&amp;gt;EnsName&amp;lt;/h2&amp;gt;
        &amp;lt;p className={`m-0 max-w-[30ch] text-sm opacity-50 text-balance`}&amp;gt;
          {ens.data || ""}
        &amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;middleEllipsis function (defined in lib/utils):&lt;/strong&gt; This custom function likely truncates long wallet addresses in the middle, displaying only the beginning and end portions for improved readability within the limited space. It takes the address string and a maximum character length as input.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;formatUnits function&lt;/strong&gt; from Viem library converts the raw balance value from the blockchain (often in wei for ETH) to a more user-friendly format with four decimal places.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By relying on Wagmi hooks (useAccount, useBalance, and useEnsName) and custom utility functions, this component effectively retrieves and displays user’s wallet address, network name (if available), balance (once fetched), and ENS name (if any). This provides users with a clear overview of their connected wallet details within our dApp.&lt;/p&gt;

&lt;p&gt;Let’s now import &lt;code&gt;ConnectBtn&lt;/code&gt; and &lt;code&gt;Profile&lt;/code&gt; in &lt;code&gt;page.tsx&lt;/code&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import Image from "next/image";
import { ConnectBtn } from "./components/connectButton";
import Profile from "./components/profile";

export default function Home() {
  return (
    &amp;lt;main className="flex min-h-screen flex-col items-center justify-between p-24"&amp;gt;
      &amp;lt;div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex"&amp;gt;
        &amp;lt;ConnectBtn /&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;div className="relative flex place-items-center before:absolute before:h-[300px] before:w-full sm:before:w-[480px] before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-full sm:after:w-[240px] after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 before:lg:h-[360px] z-[-1]"&amp;gt;
        &amp;lt;Image
          className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert"
          src="/next.svg"
          alt="Next.js Logo"
          width={180}
          height={37}
          priority
        /&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;Profile /&amp;gt;
    &amp;lt;/main&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since &lt;code&gt;middleEllipsis&lt;/code&gt; and &lt;code&gt;emojiAvatarForAddress&lt;/code&gt; functions are not provided here, kindly retrieve them in the &lt;a href="https://github.com/danmugh/wagmi-rainbowkit-nextjs-dapp"&gt;article’s repo&lt;/a&gt; on github.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This guide has empowered you to establish seamless wallet connections and fetch essential user data in your dApp. But the journey doesn’t end here! Stay tuned for Part 2, where we’ll delve into advanced features, refining your Web3/Frontend development skills and taking your dApp to the next level!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>blockchain</category>
      <category>web3</category>
      <category>nextjs</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Rust for Beginners: Dive into coding with these 5 Projects to boost your skills</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Sun, 14 Jan 2024 20:41:44 +0000</pubDate>
      <link>https://dev.to/danmugh/rust-for-beginners-dive-into-coding-with-these-5-projects-eoi</link>
      <guid>https://dev.to/danmugh/rust-for-beginners-dive-into-coding-with-these-5-projects-eoi</guid>
      <description>&lt;p&gt;Welcome to the thrilling world of Rust programming! Whether you're a coding enthusiast embarking on your programming journey or a seasoned developer eager to add a new language to your arsenal, Rust offers an exciting playground for honing your skills. In this article, I'll guide you through an engaging exploration, providing you with five hands-on projects designed specifically for beginners.&lt;/p&gt;

&lt;p&gt;Rust isn't just a programming language; it's a mindset—a commitment to performance, safety, and concurrency. As you navigate through these carefully curated projects, you'll not only grasp the fundamentals of Rust but also witness firsthand its power in creating efficient, reliable, and high-performance code.&lt;/p&gt;

&lt;p&gt;Each project serves as a stepping stone, gradually introducing you to Rust's syntax, principles, and unique features. From simple yet impactful tasks to more complex challenges, these projects are crafted to provide a well-rounded learning experience. So, buckle up and get ready to dive headfirst into the world of Rust, where your coding adventure begins!&lt;/p&gt;

&lt;p&gt;Without further ado, let's explore &lt;em&gt;"Rust for Beginners: Dive into Coding with These 5 Projects to boost your skills"&lt;/em&gt; and uncover the exciting possibilities that await you on your Rustic coding journey.&lt;/p&gt;

&lt;h2&gt;
  
  
  To-Do List App
&lt;/h2&gt;

&lt;p&gt;Building a To-Do List application in Rust is a great way to get hands-on experience with the language and its ecosystem. Below is a simple step-by-step guide to help you get started with creating a basic console-based To-Do List application in Rust.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 1: Set Up Your Rust Environment
&lt;/h4&gt;

&lt;p&gt;If you haven't installed Rust, you can do so by following the instructions on the official Rust website: &lt;a href="https://www.rust-lang.org/tools/install"&gt;https://www.rust-lang.org/tools/install&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 2: Create a New Rust Project
&lt;/h4&gt;

&lt;p&gt;Open a terminal and run the following commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new Rust project
$ cargo new todo_app

# Navigate to the project directory
$ cd todo_app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 3: Define Your To-Do Item Structure
&lt;/h4&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/strong&gt; file to define the structure for your To-Do items:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxk2zrll12tgephszsoyy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxk2zrll12tgephszsoyy.png" alt="Define Your To-Do Item Structure" width="800" height="468"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 4: Implement To-Do List Operations
&lt;/h4&gt;

&lt;p&gt;Update &lt;strong&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/strong&gt; to implement basic operations like adding, listing, and completing To-Do items:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main.rs

use std::io;

struct TodoItem {
    id: u64,
    title: String,
    completed: bool,
}

struct TodoList {
    items: Vec&amp;lt;TodoItem&amp;gt;,
}

impl TodoList {
    fn new() -&amp;gt; TodoList {
        TodoList { items: Vec::new() }
    }

    fn add_item(&amp;amp;mut self, title: String) {
        let id = self.items.len() as u64 + 1;
        let new_item = TodoItem {
            id,
            title: title.clone(),
            completed: false,
        };
        self.items.push(new_item);
        println!("Added: {}", title);
    }

    fn list_items(&amp;amp;self) {
        if self.items.is_empty() {
            println!("Your to-do list is empty.");
        } else {
            println!("Your to-do list:");
            for item in &amp;amp;self.items {
                let status = if item.completed { "[X]" } else { "[ ]" };
                println!("{} {} - {}", status, item.id, item.title);
            }
        }
    }

    fn complete_item(&amp;amp;mut self, id: u64) {
        if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
            item.completed = true;
            println!("Completed: {}", item.title);
        } else {
            println!("Item with ID {} not found.", id);
        }
    }
}

fn main() {
    let mut todo_list = TodoList::new();

    loop {
        println!("1. Add Item");
        println!("2. List Items");
        println!("3. Complete Item");
        println!("4. Exit");

        let mut choice = String::new();
        io::stdin().read_line(&amp;amp;mut choice).expect("Failed to read line");
        let choice: u32 = match choice.trim().parse() {
            Ok(num) =&amp;gt; num,
            Err(_) =&amp;gt; continue,
        };

        match choice {
            1 =&amp;gt; {
                println!("Enter the title of the new item:");
                let mut title = String::new();
                io::stdin().read_line(&amp;amp;mut title).expect("Failed to read line");
                todo_list.add_item(title.trim().to_string());
            }
            2 =&amp;gt; {
                todo_list.list_items();
            }
            3 =&amp;gt; {
                println!("Enter the ID of the completed item:");
                let mut id = String::new();
                io::stdin().read_line(&amp;amp;mut id).expect("Failed to read line");
                let id: u64 = match id.trim().parse() {
                    Ok(num) =&amp;gt; num,
                    Err(_) =&amp;gt; continue,
                };
                todo_list.complete_item(id);
            }
            4 =&amp;gt; {
                println!("Exiting the program.");
                break;
            }
            _ =&amp;gt; {
                println!("Invalid choice. Please enter a number between 1 and 4.");
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 5: Run Your To-Do List Application
&lt;/h4&gt;

&lt;p&gt;Run your application using:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cargo run&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Follow the on-screen instructions to add, list, and complete To-Do items in your Rust To-Do List application.&lt;/p&gt;
&lt;h2&gt;
  
  
  Calculator App
&lt;/h2&gt;

&lt;p&gt;Building a basic calculator in Rust is a great way to practice the language and its fundamental concepts. &lt;/p&gt;
&lt;h4&gt;
  
  
  Step 1: Set Up Your Rust Environment
&lt;/h4&gt;
&lt;h4&gt;
  
  
  Step 2: Create a New Rust Project
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new Rust project
$ cargo new calculator_app
$ cd calculator_app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Step 3: Implement the Calculator Logic
&lt;/h4&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/strong&gt; file to implement the calculator logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main.rs

use std::io;

fn main() {
    loop {
        println!("Simple Calculator");
        println!("1. Addition");
        println!("2. Subtraction");
        println!("3. Multiplication");
        println!("4. Division");
        println!("5. Exit");

        let mut choice = String::new();
        io::stdin().read_line(&amp;amp;mut choice).expect("Failed to read line");
        let choice: u32 = match choice.trim().parse() {
            Ok(num) =&amp;gt; num,
            Err(_) =&amp;gt; continue,
        };

        if choice == 5 {
            println!("Exiting the calculator.");
            break;
        }

        println!("Enter the first number:");
        let mut num1 = String::new();
        io::stdin().read_line(&amp;amp;mut num1).expect("Failed to read line");
        let num1: f64 = match num1.trim().parse() {
            Ok(num) =&amp;gt; num,
            Err(_) =&amp;gt; {
                println!("Invalid input. Please enter a valid number.");
                continue;
            }
        };

        println!("Enter the second number:");
        let mut num2 = String::new();
        io::stdin().read_line(&amp;amp;mut num2).expect("Failed to read line");
        let num2: f64 = match num2.trim().parse() {
            Ok(num) =&amp;gt; num,
            Err(_) =&amp;gt; {
                println!("Invalid input. Please enter a valid number.");
                continue;
            }
        };

        match choice {
            1 =&amp;gt; {
                let result = num1 + num2;
                println!("Result: {}", result);
            }
            2 =&amp;gt; {
                let result = num1 - num2;
                println!("Result: {}", result);
            }
            3 =&amp;gt; {
                let result = num1 * num2;
                println!("Result: {}", result);
            }
            4 =&amp;gt; {
                if num2 != 0.0 {
                    let result = num1 / num2;
                    println!("Result: {}", result);
                } else {
                    println!("Error: Division by zero.");
                }
            }
            _ =&amp;gt; {
                println!("Invalid choice. Please enter a number between 1 and 5.");
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 4: Run Your Calculator
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;cargo run&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Simple Blog Platform
&lt;/h2&gt;

&lt;p&gt;Building a simple blog platform in Rust involves creating a web server, handling HTTP requests, and interacting with a database. Here, I'll guide you through creating a basic blog platform using the Actix web framework and SQLite as the database. &lt;/p&gt;

&lt;p&gt;Note that this is a minimal example for learning purposes. In a real-world scenario, you'd want to consider security, user authentication, and additional features.&lt;/p&gt;
&lt;h4&gt;
  
  
  Step 1: Set Up Your Rust Environment
&lt;/h4&gt;
&lt;h4&gt;
  
  
  Step 2: Create a New Rust Project
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new Rust project
$ cargo new new simple_blog
$ cd new simple_blog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Step 3: Add Dependencies to Cargo.toml
&lt;/h4&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;Cargo.toml&lt;/code&gt;&lt;/strong&gt; file to include the necessary dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[dependencies]
actix-web = "4.0"
actix-rt = "2.5"
sqlx = "0.5"
sqlx-core = "0.5"
sqlx-migrate = "0.5"
sqlx-derive = "0.5"
dotenv = "0.17"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run &lt;strong&gt;&lt;code&gt;cargo build&lt;/code&gt;&lt;/strong&gt; to fetch and build the dependencies.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 4: Set Up Your Database
&lt;/h4&gt;

&lt;p&gt;Create a &lt;strong&gt;&lt;code&gt;.env&lt;/code&gt;&lt;/strong&gt; file in your project directory with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DATABASE_URL=sqlite:./blog.db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 5: Define the Database Schema
&lt;/h4&gt;

&lt;p&gt;Create a &lt;strong&gt;&lt;code&gt;migrations&lt;/code&gt;&lt;/strong&gt; directory and add a file named &lt;strong&gt;&lt;code&gt;20220101000000_init.sql&lt;/code&gt;&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- migrations/20220101000000_init.sql

-- create the posts table
CREATE TABLE posts (
    id INTEGER PRIMARY KEY,
    title TEXT NOT NULL,
    content TEXT NOT NULL
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 6: Set Up Database Connection
&lt;/h4&gt;

&lt;p&gt;Create a &lt;strong&gt;&lt;code&gt;src/db.rs&lt;/code&gt;&lt;/strong&gt; file for handling the database connection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/db.rs

use sqlx::sqlite::SqlitePool;
use sqlx::Pool;
use std::env;

pub async fn init_pool() -&amp;gt; Pool&amp;lt;SqlitePool&amp;gt; {
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env");
    SqlitePool::connect(&amp;amp;database_url)
        .await
        .expect("Failed to connect to the database")
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 7: Implement the Blog Platform
&lt;/h4&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/strong&gt; file with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main.rs

use actix_web::{web, App, HttpServer, Responder};
use sqlx::sqlite::SqlitePool;
use sqlx::Row;
use dotenv::dotenv;

mod db;

async fn index(pool: web::Data&amp;lt;SqlitePool&amp;gt;) -&amp;gt; impl Responder {
    let mut conn = pool.acquire().await.expect("Failed to acquire a database connection");

    let result = sqlx::query!("SELECT id, title, content FROM posts")
        .fetch_all(&amp;amp;mut conn)
        .await
        .expect("Failed to fetch posts from the database");

    let posts: Vec&amp;lt;String&amp;gt; = result
        .iter()
        .map(|row| format!("{}: {}\n{}", row.id, row.title, row.content))
        .collect();

    posts.join("\n")
}

#[actix_web::main]
async fn main() -&amp;gt; std::io::Result&amp;lt;()&amp;gt; {
    dotenv().ok();

    let pool = db::init_pool().await;

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(pool.clone()))
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 8: Run the Application
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;cargo run&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Visit &lt;a href="http://127.0.0.1:8080"&gt;http://127.0.0.1:8080&lt;/a&gt; to see your simple blog platform in action.&lt;/p&gt;

&lt;p&gt;This is a basic example, and you can extend it by adding features such as creating, updating, and deleting posts, handling user authentication, and improving the frontend using a front-end framework. Remember to handle errors and ensure security in a production environment.&lt;/p&gt;
&lt;h2&gt;
  
  
  Weather App
&lt;/h2&gt;

&lt;p&gt;Building a weather app in Rust involves interacting with a weather API to fetch real-time weather data and presenting it to users. Here's a simple example using the Actix web framework and the OpenWeatherMap API.&lt;/p&gt;
&lt;h4&gt;
  
  
  Step 1: Set Up Your Rust Environment
&lt;/h4&gt;
&lt;h4&gt;
  
  
  Step 2: Create a New Rust Project
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new Rust project
$ cargo new weather_app
$ cd weather_app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h4&gt;
  
  
  Step 3: Add Dependencies to Cargo.toml
&lt;/h4&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;Cargo.toml&lt;/code&gt;&lt;/strong&gt; file to include the necessary dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[dependencies]
actix-web = "4.0"
reqwest = "0.11"
serde = "1.0"
serde_json = "1.0"
dotenv = "0.17"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run &lt;strong&gt;&lt;code&gt;cargo build&lt;/code&gt;&lt;/strong&gt; to fetch and build the dependencies.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 4: Set Up Your OpenWeatherMap API Key
&lt;/h4&gt;

&lt;p&gt;Create a &lt;strong&gt;&lt;code&gt;.env&lt;/code&gt;&lt;/strong&gt; file in your project directory with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OPENWEATHERMAP_API_KEY=your_api_key_here

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace &lt;strong&gt;&lt;code&gt;your_api_key_here&lt;/code&gt;&lt;/strong&gt; with your actual OpenWeatherMap API key.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 5: Implement the Weather App
&lt;/h4&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/strong&gt; file with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main.rs

use actix_web::{web, App, HttpServer, HttpResponse};
use reqwest::Client;
use serde::Deserialize;
use std::env;

#[derive(Deserialize)]
struct WeatherResponse {
    main: Main,
    name: String,
}

#[derive(Deserialize)]
struct Main {
    temp: f32,
}

async fn index() -&amp;gt; HttpResponse {
    let api_key = env::var("OPENWEATHERMAP_API_KEY").expect("OPENWEATHERMAP_API_KEY is not set in .env");
    let city = "London"; // You can replace this with the desired city

    let url = format!(
        "http://api.openweathermap.org/data/2.5/weather?q={}&amp;amp;appid={}&amp;amp;units=metric",
        city, api_key
    );

    let response = Client::new().get(&amp;amp;url).send().await;

    match response {
        Ok(res) =&amp;gt; {
            let weather_data: WeatherResponse = res.json().await.expect("Failed to parse JSON response");

            let temperature = weather_data.main.temp;
            let city_name = weather_data.name;

            HttpResponse::Ok().body(format!("Weather in {}: {:.1}°C", city_name, temperature))
        }
        Err(_) =&amp;gt; HttpResponse::InternalServerError().body("Failed to fetch weather data"),
    }
}

#[actix_web::main]
async fn main() -&amp;gt; std::io::Result&amp;lt;()&amp;gt; {
    dotenv::dotenv().ok();

    HttpServer::new(|| {
        App::new().route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 6: Run the Application
&lt;/h4&gt;

&lt;p&gt;&lt;code&gt;cargo run&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Visit &lt;a href="http://127.0.0.1:8080"&gt;http://127.0.0.1:8080&lt;/a&gt; to see the current weather in the specified city.&lt;/p&gt;

&lt;p&gt;This serves as a foundation; consider refining it by incorporating user city input, refining error handling, and enhancing the frontend with a robust framework. Prioritize error management and security measures for production readiness.&lt;/p&gt;
&lt;h2&gt;
  
  
  Budget Manager App
&lt;/h2&gt;

&lt;p&gt;Building a simple budget manager in Rust involves creating a command-line application that allows users to manage their income, expenses, and view the overall budget. Here's a basic example to get you started:&lt;/p&gt;
&lt;h4&gt;
  
  
  Step 1: Set Up Your Rust Environment
&lt;/h4&gt;
&lt;h4&gt;
  
  
  Step 2: Create a New Rust Project
&lt;/h4&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cargo new budget_manager
cd budget_manager
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Step 3: Implement the Budget Manager
&lt;/h2&gt;

&lt;p&gt;Edit the &lt;strong&gt;&lt;code&gt;src/main.rs&lt;/code&gt;&lt;/strong&gt; file with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main.rs

use std::io;

struct BudgetManager {
    income: f64,
    expenses: f64,
}

impl BudgetManager {
    fn new() -&amp;gt; Self {
        Self {
            income: 0.0,
            expenses: 0.0,
        }
    }

    fn add_income(&amp;amp;mut self, amount: f64) {
        self.income += amount;
        println!("Income added: ${}", amount);
    }

    fn add_expense(&amp;amp;mut self, amount: f64) {
        self.expenses += amount;
        println!("Expense added: ${}", amount);
    }

    fn view_budget(&amp;amp;self) {
        let balance = self.income - self.expenses;
        println!("Income: ${}", self.income);
        println!("Expenses: ${}", self.expenses);
        println!("Balance: ${}", balance);
    }
}

fn main() {
    let mut budget_manager = BudgetManager::new();

    loop {
        println!("Budget Manager");
        println!("1. Add Income");
        println!("2. Add Expense");
        println!("3. View Budget");
        println!("4. Exit");

        let mut choice = String::new();
        io::stdin().read_line(&amp;amp;mut choice).expect("Failed to read line");
        let choice: u32 = match choice.trim().parse() {
            Ok(num) =&amp;gt; num,
            Err(_) =&amp;gt; continue,
        };

        match choice {
            1 =&amp;gt; {
                println!("Enter the income amount:");
                let mut amount = String::new();
                io::stdin().read_line(&amp;amp;mut amount).expect("Failed to read line");
                let amount: f64 = match amount.trim().parse() {
                    Ok(num) =&amp;gt; num,
                    Err(_) =&amp;gt; continue,
                };
                budget_manager.add_income(amount);
            }
            2 =&amp;gt; {
                println!("Enter the expense amount:");
                let mut amount = String::new();
                io::stdin().read_line(&amp;amp;mut amount).expect("Failed to read line");
                let amount: f64 = match amount.trim().parse() {
                    Ok(num) =&amp;gt; num,
                    Err(_) =&amp;gt; continue,
                };
                budget_manager.add_expense(amount);
            }
            3 =&amp;gt; {
                budget_manager.view_budget();
            }
            4 =&amp;gt; {
                println!("Exiting the budget manager.");
                break;
            }
            _ =&amp;gt; {
                println!("Invalid choice. Please enter a number between 1 and 4.");
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step 4: Run the Application
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;cargo run&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Follow the on-screen instructions to add income, expenses, and view your budget.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Feel free to enhance and customize the applications based on your learning goals and preferences. This is a basic example to get you started with Rust programming. If you have any questions or want to share your thoughts, please feel free to leave a comment or reach out to me. Let's continue to explore the vast possibilities of Rust together.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>rust</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Rust Tips and Tricks #PartOne</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Sat, 08 Apr 2023 08:21:58 +0000</pubDate>
      <link>https://dev.to/danmugh/rust-tips-and-tricks-partone-1ic4</link>
      <guid>https://dev.to/danmugh/rust-tips-and-tricks-partone-1ic4</guid>
      <description>&lt;p&gt;Rust is a programming language that has gained a reputation for its exceptional qualities in terms of reliability, speed, and overall enjoyment for the programmer. However, it is important to keep in mind that Rust is also recognized as a language with a relatively high level of complexity.&lt;/p&gt;

&lt;p&gt;As programmers, when we start using a new language, we tend to apply the concepts and techniques we have learned from our previous language experiences. Initially, we may not be familiar with the idiomatic way of writing code, nor the efficient shortcuts that the new language offers. Nevertheless, we manage to make progress by experimenting with the code until it runs and compiles.&lt;/p&gt;

&lt;p&gt;This is perfectly natural. Over time, by seeing other people’s code, we learn, we adapt, and we write better code. This post tries to speed up that process by showing you some of the Rust shorthands I have discovered so far.&lt;/p&gt;

&lt;h2&gt;
  
  
  Avoid unnecessary clones
&lt;/h2&gt;

&lt;p&gt;When a variable is cloned using the .clone() method, its data is duplicated, which requires additional resources. As a result, clones typically have a detrimental impact on performance and should be used sparingly. In many cases, it is possible to pass references to the same variables to different functions, eliminating the need for cloning. For example :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnvigzdnf9iolwio7r468.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnvigzdnf9iolwio7r468.png" alt="Avoid unnecessary clones codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using Cow as return type
&lt;/h2&gt;

&lt;p&gt;Occasionally, you may need to write methods that accept a string slice (&amp;amp;str) as input and possibly return either an altered version of the input or the original string.&lt;/p&gt;

&lt;p&gt;In such situations, the Cow type can prove to be useful since it allows you to avoid allocating new memory unnecessarily. By using Cow, you can modify the input string when needed, but if no changes are required, the original string can be returned without incurring any additional memory allocation costs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fztsh16o74y2x52qvb42h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fztsh16o74y2x52qvb42h.png" alt="Using Cow&amp;lt;str&amp;gt; codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Enum size is bounded by the largest member
&lt;/h2&gt;

&lt;p&gt;To ensure that an Enum can accommodate its largest variant, its size is determined accordingly. To optimize memory usage, it is advisable to keep the variants within an Enum of similar sizes. However, if necessary, larger variants can be boxed. Consider this example :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx1dokwvikcogs22ck4o5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx1dokwvikcogs22ck4o5.png" alt="Enum codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using dbg!() macro instead of println!()
&lt;/h2&gt;

&lt;p&gt;The &lt;a href="https://doc.rust-lang.org/stable/std/macro.dbg.html" rel="noopener noreferrer"&gt;dbg macro&lt;/a&gt; can be used to print the value as well as the source code of an express to stderr. Example usage:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft9ait0n6igsh0v1ahbls.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft9ait0n6igsh0v1ahbls.png" alt="dbg!() macro codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The above code will print :&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;2&lt;br&gt;
[src/main.rs:5] var1 = 2&lt;br&gt;
Output: [src/main.rs:6] var1 * 2 = 4&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Crossbeam channels instead of the standard ones&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;The &lt;a href="https://github.com/crossbeam-rs/crossbeam" rel="noopener noreferrer"&gt;crossbeam crate&lt;/a&gt; offers a powerful alternative to standard channels with support for the Select operation, timeouts, and more.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs3w2wjmnhkwt8sq9mvf1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs3w2wjmnhkwt8sq9mvf1.png" alt="Crossbeam channels codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Customize and chain Panic handlers
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://doc.rust-lang.org/std/panic/fn.set_hook.html" rel="noopener noreferrer"&gt;Panic handlers (called hooks)&lt;/a&gt; can be overridden and chained, which becomes particularly useful when setting up custom error reporting and logging for your application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkv8po37m4rzvxsrlqmac.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkv8po37m4rzvxsrlqmac.png" alt="Customize and chain Panic handlers codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Output :&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;custom error reporting logic panicked at 'test', src/main.rs:20:5&lt;br&gt;
custom logging logic panicked at 'test', src/main.rs:20:5&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  The standard swap function&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;The swap function allows you to directly swap two variables without needing to create a temporary variable.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foiulxs8zz6aqxy6ih22j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foiulxs8zz6aqxy6ih22j.png" alt="The standard swap function codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Use impl Trait when working with Closures
&lt;/h2&gt;

&lt;p&gt;When passing a closure to a function, it is generally better to use the “impl Fn/FnOnce/FnMut” approach instead of a generic one. This approach, also known as “impl Trait,” helps keep the function’s signature uncluttered. In more complex scenarios, however, you may need to box the closure with “Box” to make it work. It is essential to keep in mind that boxing a closure can introduce additional overhead, which may be undesirable in some cases.&lt;/p&gt;

&lt;p&gt;Therefore, it is important to weigh the benefits and drawbacks of each approach and choose the one that best suits your requirements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbgpzwhlkqsm5mvhb9k82.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbgpzwhlkqsm5mvhb9k82.png" alt="impl Trait with Closures codesnap illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Output :&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

&lt;p&gt;setting up...&lt;br&gt;
Action!&lt;br&gt;
tearing down...&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Clippy and rustfmt&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;They are two of my favorite Rust tools. If you haven’t tried them yet, I highly recommend giving them a try. Clippy can detect various lints in your code and guide you towards writing more idiomatic code. To install Clippy, simply run rustup component add clippy, and to run it within your workspace, execute cargo clippy. For more details, visit &lt;a href="https://github.com/rust-lang/rust-clippy" rel="noopener noreferrer"&gt;Clippy’s GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Rustfmt is a tool that formats Rust code in compliance with style guidelines. Its name precisely reflects its purpose. To install rustfmt, you can run rustup component add rustfmt. Once installed, you can execute cargo fmt to format Rust code in your workspace. If you require further information, you can visit &lt;a href="https://github.com/rust-lang/rustfmt" rel="noopener noreferrer"&gt;rustfmt’s GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Simplify Your Rust Error Handling with &lt;strong&gt;“thiserror”&lt;/strong&gt; and &lt;strong&gt;“anyhow”&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;When it comes to handling errors in Rust, it is often best to use the &lt;strong&gt;“thiserror”&lt;/strong&gt; and &lt;strong&gt;“anyhow”&lt;/strong&gt; crates for an idiomatic approach. &lt;strong&gt;“Thiserror”&lt;/strong&gt; is useful when the consumer of the error needs to take action based on specific error conditions.&lt;/p&gt;

&lt;h2&gt;
  
  
  CONCLUSION
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Rust is a programming language with immense potential, and it has something new to offer every day. I hope that this post has provided you with valuable insights into Rust and helped you learn something new. If you have any questions or want to share your thoughts, please feel free to leave a comment or reach out to me. &lt;strong&gt;Let’s continue to explore the vast possibilities of Rust together.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>rust</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Borrowing and Referencing in Rust</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Sun, 26 Feb 2023 06:25:45 +0000</pubDate>
      <link>https://dev.to/danmugh/borrowing-and-referencing-in-rust-1egd</link>
      <guid>https://dev.to/danmugh/borrowing-and-referencing-in-rust-1egd</guid>
      <description>&lt;p&gt;Borrowing and Ownership are intimately related concepts that play a vital role in memory management in Rust. Therefore, comprehending borrowing is crucial for working effectively in Rust.&lt;/p&gt;

&lt;p&gt;In order to maintain memory safety, Rust uses a borrow checker to enforce its ownership rules. The ownership rules dictate how Rust manages memory over the stack and heap.&lt;/p&gt;

&lt;p&gt;Most of the time, we'd like to access some data without taking ownership over it. To accomplish this, Rust provides a borrowing mechanism. Instead of passing objects by-value (T), objects can be passed by reference (&amp;amp;T).&lt;/p&gt;

&lt;p&gt;In this Rust tutorial we will learn how to borrow a value temporarily from its owner, which allows us to have multiple references to that value without breaking ownership. We'll also learn about referencing the memory address of a value and how to get the value at that address with the dereferencing operator.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Borrowing ?
&lt;/h2&gt;

&lt;p&gt;If we want to use a value in a function, without transferring ownership to the function, we can borrow the value temporarily from its owner. When the function is done with the value, it’s given back to the owner.&lt;/p&gt;

&lt;p&gt;Borrowing allows us to have one or more references to a single value without breaking the “single owner” concept.&lt;br&gt;
When we borrow a value, we reference its memory address with the &amp;amp; operator. A reference in Rust is an address that is passed to a function as an argument.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flg4skvuj1lbah7ukep9v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flg4skvuj1lbah7ukep9v.png" alt=" " width="800" height="369"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Inside print_vector function [10, 20, 30]
Printing the value from main() v[0] = 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Mutable References
&lt;/h2&gt;

&lt;p&gt;A function can modify a borrowed resource by using a mutable reference to such resource. A mutable reference is prefixed with &lt;strong&gt;&amp;amp;mut&lt;/strong&gt;. Mutable references can operate only on mutable variables.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F15xs57i9nax8sr9i6ydl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F15xs57i9nax8sr9i6ydl.png" alt=" " width="800" height="378"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;main()&lt;/strong&gt; function passes a mutable reference of the variable &lt;strong&gt;name to the display()&lt;/strong&gt; function. The display function appends an additional string to the original name variable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;param_name value is : Hello
The value of name after modification is: Hello World
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Borrow and Reference a value from variable
&lt;/h2&gt;

&lt;p&gt;In Rust, the memory address of a value can be referenced using the &lt;strong&gt;&amp;amp;&lt;/strong&gt; operator. To understand this concept better, let's take a look at an example.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmugc9u41b3wa8coo418n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmugc9u41b3wa8coo418n.png" alt=" " width="800" height="419"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the example above, the variable a is the owner of the String &lt;strong&gt;Hello&lt;/strong&gt;. If we use the variable in a function, it will pass ownership to the function. In this case we don’t want that, so the solution is to reference the owner (a) instead.&lt;/p&gt;

&lt;p&gt;In the parameter list of the function definition, we add the &lt;strong&gt;&amp;amp;&lt;/strong&gt; parameter before the type to tell Rust that the value coming in will be a reference to a value, not the actual value. The function only borrows the value, and gives it back after the function completes its execution.&lt;/p&gt;

&lt;p&gt;When we call the function, we have to add the &amp;amp; operator again, this time in front of the value that we pass.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Understanding Ownership and Borrowing is crucial for writing efficient and memory-safe Rust code that compiles and runs without errors.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Failure to adhere to the ownership rules will be detected by the borrow checker, requiring you to modify your code to make it memory-safe before Rust will compile it. The borrow checker is annoying when you’re new to Rust. But, as you write more Rust code, you’ll get used to it and gain experience on writing memory-safe Rust code.&lt;/p&gt;




&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/" rel="noopener noreferrer"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>redis</category>
      <category>challenge</category>
      <category>coop</category>
    </item>
    <item>
      <title>Ownership in Rust</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Sun, 19 Feb 2023 13:08:26 +0000</pubDate>
      <link>https://dev.to/danmugh/ownership-in-rust-301o</link>
      <guid>https://dev.to/danmugh/ownership-in-rust-301o</guid>
      <description>&lt;p&gt;For the fifth consecutive year, Rust has been ranked as &lt;a href="https://insights.stackoverflow.com/survey/2020#technology-most-loved-dreaded-and-wanted-languages-loved"&gt;the most loved programming language&lt;/a&gt; in a survey of developers conducted by Stack Overflow. There are various reasons why developers love Rust, in one of my first articles of 2022, &lt;em&gt;&lt;a href="https://medium.com/@danmugh/genesis-in-rust-getting-started-bfd348665d9"&gt;Genesis in Rust&lt;/a&gt;&lt;/em&gt; I mentioned that one of the most attractive features of Rust is its &lt;strong&gt;Safety&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Rust uses a system of ownership and borrowing to manage memory at compile time, rather than relying on garbage collection or manual memory management. Ownership refers to a set of rules that determine which part of a program is responsible for managing a particular piece of memory, and when that memory can be freed. In this article we will dive into Ownership and later on Borrowing in the next article.&lt;/p&gt;

&lt;p&gt;In Rust, each value has a single owner at any given time. When a value is assigned to a variable or passed as an argument to a function, the ownership of that value is transferred to the new variable or function parameter. When the owner goes out of scope (i.e., when the variable is no longer in use), Rust automatically frees the memory associated with that value by inserting a drop statement.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqs33alsu1tdx0xhs5mpu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqs33alsu1tdx0xhs5mpu.png" alt="Code illustration" width="800" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This approach ensures that memory is always properly managed and avoids common issues such as null pointer errors or memory leaks. Additionally, Rust’s borrowing system allows for safe and efficient sharing of memory between different parts of a program, without the need for costly runtime checks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Stack and the Heap&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The stack and the heap are two different regions of memory that are used to store values in different ways.&lt;/p&gt;

&lt;p&gt;The stack is a region of memory used for storing data that has a known size at compile time and a relatively short lifetime. Examples of data stored on the stack include function arguments, local variables, and function return values. The stack operates in a last-in-first-out (LIFO) manner, meaning that the last item added to the stack is the first one to be removed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpukd47lfg0cylh70p4zl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpukd47lfg0cylh70p4zl.png" alt="Last-in-first-out illustration" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The heap, on the other hand, is a region of memory used to store data that needs to persist beyond the lifetime of a single function call. Memory allocated on the heap is not automatically managed by the Rust compiler and must be manually managed using pointers. Heap memory is allocated and freed using Rust’s Box type, which provides a way to allocate memory on the heap and automatically free it when the Box is dropped.&lt;/p&gt;

&lt;p&gt;Rust provides several different types of pointers that can be used to interact with heap-allocated data, including references, boxes, and smart pointers such as Rc and Arc. Rust’s ownership model ensures that heap-allocated data is always properly managed, with memory being freed automatically when it is no longer needed. This approach helps to prevent many common memory-related bugs, such as use-after-free errors, buffer overflows, and null pointer dereferences.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Overall, the stack and the heap are two distinct regions of memory in Rust that are used to store data in different ways as mentioned , with the stack being used for short-lived data of a fixed size, and the heap being used for dynamically allocated data of varying size and longer lifetime.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;How ownership works&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Rust compiler enforces ownership rules at compile time, checking that all values have a valid owner and that there are no ownership violations such as multiple owners of a single value. This helps to ensure that Rust code is free from common memory management errors, making it safer and more reliable than other programming languages.&lt;/p&gt;

&lt;p&gt;It is crucial to understand the three basic rules of ownership, which determine how memory is stored in the stack and heap.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Each Rust value has a variable called its owner :
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 67; // x is the owner of the value "67"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Ownership can be transferred between variables via moves, which transfer ownership of the value to the new variable and invalidate the original variable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When the owner goes out of the scope, the value it owns is dropped (i.e., memory is freed) :&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcnq04kstbiqaa602704z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcnq04kstbiqaa602704z.png" alt="Code illustration" width="800" height="301"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In our introduction, we established a fact that ownership isn’t like the garbage collector system and, in fact, Rust doesn’t deal with a garbage collector system. Most programming languages either use a garbage collector or require the developer to allocate and free up memory themselves.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ownership and functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When values are passed to a function, they must follow the same ownership rules as other values. Meaning they can only have one owner at a time, and free up memory once out of scope.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1alhl3tzc78wij6ae3xa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1alhl3tzc78wij6ae3xa.png" alt="Code illustration" width="800" height="676"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The second rule of ownership, which states that a value can only have one owner at a time, results in verbose function writing. This is due to the need to transfer ownership of functions through return statements whenever you want to use them, as illustrated in the example above.&lt;/p&gt;

&lt;p&gt;It is very memory-inefficient to make copies of data whenever passing to a function. The best method is to use &lt;a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html"&gt;the Rust references&lt;/a&gt; feature and borrow the data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rust’s ownership feature is a critical aspect of the language that can greatly impact a developer’s ability to create scalable code. The more comfortable a Rust programmer becomes with ownership, the easier it becomes for him or her to write scalable and predictable code, which in turn can help to avoid unexpected errors or bugs. Many developers appreciate Rust specifically because of its strong ownership model, which helps prevent unexpected behaviour.&lt;/p&gt;

&lt;p&gt;In this article, we’ve explored the fundamentals of ownership in Rust, including its rules and best practices for incorporating it into our programs. Additionally, we’ve discussed certain Rust features that don’t rely on ownership, and how to use them effectively. For additional resources on Rust ownership, be sure to consult &lt;a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html"&gt;the official documentation&lt;/a&gt; to deepen your understanding and enhance your coding skills.&lt;/p&gt;




&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>rust</category>
      <category>memory</category>
      <category>programming</category>
    </item>
    <item>
      <title>Genesis in Rust: Getting Started</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Sat, 16 Apr 2022 22:38:45 +0000</pubDate>
      <link>https://dev.to/danmugh/genesis-in-rust-getting-started-524p</link>
      <guid>https://dev.to/danmugh/genesis-in-rust-getting-started-524p</guid>
      <description>&lt;p&gt;Rust is a systems programming language that focuses on speed, memory safety, and parallelism. Rust is the super productive, super safe, and super fast language &lt;strong&gt;that breaks the trend of marginal improvements&lt;/strong&gt;. It changes the way you think about software development.&lt;/p&gt;

&lt;p&gt;Rust puts developers first by providing features that make software development smooth and reliable. This includes maintenance, which is a large part of a project's lifecycle.&lt;/p&gt;

&lt;p&gt;This is where Rust shines. Rust combines ease of programming with access to core system configurations. Rust is built with memory-safety, concurrency, and security from the ground up.&lt;/p&gt;

&lt;p&gt;Since Rust can run both on the backend (natively) and frontend (via Wasm) of web applications, learning Rust becomes a clear choice for creating performant and reliable web applications that can be accessed anywhere, and on any device.&lt;/p&gt;

&lt;p&gt;Rust is used by some of the top tech companies like Amazon, Microsoft Corporation, Dropbox, Cloudflare, Figma, Discord, Mozilla and Facebook to deliver speed and concurrency to their customers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let's look at some core features that make Rust stand out from other programming languages.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rust is a really fast and memory-efficient language. It offers fine-grained control of memory management and has a minimal standard library. So it can perform well with critical services, within embedded devices, and easily be integrated with other languages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Security&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using Rust eliminates an entire class of security vulnerabilities from software applications. This helps companies build applications with better performance and higher security. This is a great relief to any new programmer, as it reduces the burden while compiling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Concurrency&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Concurrency is when two or more tasks start, run, and complete in overlapping time. Database operations are a great example to explain concurrency. When thousands of users are using your application at the same time to perform different actions, your database handles them concurrently. Concurrency is a key concept when it comes to scaling applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;This article will guide you through setting up Rust and getting started.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting started
&lt;/h2&gt;

&lt;p&gt;Now that you understand the core features of Rust, let's setting up. You can find &lt;a href="https://www.rust-lang.org/tools/install"&gt;installation instructions here&lt;/a&gt; follow the instructions to continue the installation.&lt;/p&gt;

&lt;p&gt;Now open your IDE, I use WebStorm as my IDE because it provides a robust, fast, and flexible static code analysis and actually provides a lot of support for Rust.&lt;/p&gt;

&lt;p&gt;Let's start with a simple “Hello World!” function. Create a new file with the name "main.rs" extension&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2m7tv1bugk2l72qa55vm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2m7tv1bugk2l72qa55vm.png" alt="Image description" width="800" height="425"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now open the main.rs and type the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main( ) {
    println!("Hello, world!");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;em&gt;&lt;strong&gt;fn&lt;/strong&gt; is used to declare a function in Rust&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The &lt;strong&gt;main&lt;/strong&gt; function is special: it's the beginning of every Rust program&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;The line ends with a semicolon &lt;strong&gt;(;)&lt;/strong&gt;. The ; indicates that this expression is over, and the next one is ready to begin. Most lines of Rust code end with a &lt;strong&gt;;&lt;/strong&gt;&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Save the file, open your terminal and enter the following commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$   rustc main.rs
$   ./main
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Before running a Rust program, you have to compile it. You can use the Rust compiler by entering the rustc command and passing it the name of your source file&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And you should see the string &lt;strong&gt;Hello, world!&lt;/strong&gt; print to the terminal. If you did, then congratulations! You've officially written a your first Rust program 👏🎊&lt;/p&gt;

&lt;h2&gt;
  
  
  Project management with Cargo
&lt;/h2&gt;

&lt;p&gt;To create your first project using Cargo, you invoke the cargo executable with keyword new and lastly with the name of the project like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$   cargo new project-name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s check out what Cargo has generated for us:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$   cd project-name
$   tree .
 .
 ├── Cargo.toml
 └── src
       └── main.rs

1 directory, 2 files
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F51433y2lpn35nfbbqgx8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F51433y2lpn35nfbbqgx8.png" alt="Image description" width="800" height="496"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;main.rs&lt;/strong&gt; is our projects main file, the entry for our app. Here's what main.rs contains:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main( ) {
    println!("Hello, world!");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Cargo generated a &lt;strong&gt;hello, world!&lt;/strong&gt; for us&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s take a closer look at &lt;strong&gt;Cargo.toml&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
   [package]
   name = "project-name"
   version = "0.1.0"
   authors = ["email, inferred from Git"]
   edition = "2018"

   # See more keys and their definitions at https://doc.rustlang.org/cargo/reference/manifest.html

   [dependencies]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;em&gt;This is called a manifest, and it contains all of the metadata that Cargo needs to compile your project.&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Now let’s build and run the code
&lt;/h2&gt;

&lt;p&gt;To build and run your project, call cargo run in your project directory root:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$   cargo run
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should get this output :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1m3hhrcc4puv77fo0rep.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1m3hhrcc4puv77fo0rep.png" alt="Image description" width="800" height="165"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources to help you
&lt;/h2&gt;

&lt;p&gt;Afterward, practice coding with &lt;a href="https://exercism.org/users/sign_in"&gt;Exercism&lt;/a&gt; to improve your Rust chops together with reading a more extensive resource like &lt;a href="https://doc.rust-lang.org/book/"&gt;the Rust book&lt;/a&gt; (standard choice) or &lt;a href="https://dhghomon.github.io/easy_rust/"&gt;Easy Rust&lt;/a&gt; (accessible choice). At any point where you feel that you are almost ready to build your own toy applications, just go ahead and do it. There are some nice online communities to ask for feedback and support, so don’t be worried about getting stuck!&lt;/p&gt;




&lt;p&gt;☞ Follow me on &lt;a href="https://twitter.com/danmugh"&gt;Twitter&lt;/a&gt; &amp;amp; &lt;a href="https://www.linkedin.com/in/dan-mugisho-m-b20b37228/"&gt;Linkedin&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;☞ Kindly subscribe for my upcoming articles&lt;/p&gt;

</description>
      <category>rust</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>career</category>
    </item>
    <item>
      <title>Angular vs React vs Vue : Which to choose for your career as a UI developer</title>
      <dc:creator>Dan Mugisho M.</dc:creator>
      <pubDate>Tue, 29 Mar 2022 03:20:53 +0000</pubDate>
      <link>https://dev.to/danmugh/angular-vs-react-vs-vue-which-to-choose-for-your-career-as-a-ui-developer-283i</link>
      <guid>https://dev.to/danmugh/angular-vs-react-vs-vue-which-to-choose-for-your-career-as-a-ui-developer-283i</guid>
      <description>&lt;p&gt;&lt;strong&gt;Angular vs. React vs. Vue is one of primary choices in every web development process. The frontend framework you select influences almost everything: speed, and, therefore, cost of development, compatibility with other technologies, app speed and performance, and so on.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As a developer, you definitely heard about Angular, React, and Vue and the constant discussions and comparisons around which one is better. Of course, all three of them are used for building web, mobile apps, and fast development of UI through the use of components.&lt;/p&gt;

&lt;p&gt;We’ll start with a little bit of theory. In web development, we always differentiate between frontend and backend. The frontend is the part of the website that users see in their browser. The backend, accordingly, is behind the scenes and is usually responsible for the business logic of the web app.&lt;/p&gt;

&lt;p&gt;A software framework (be it frontend or backend) includes standardized pre-written code, making the development of certain functionality easier and faster.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Angular&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;AngularJS is a TypeScript based JavaScript framework that was initially released by Google in 2010. It is the oldest one among the lot we are covering in this article.&lt;/p&gt;

&lt;p&gt;In 2016, Angular (also known as Angular 2) was released and “JS” was dropped from the framework’s name. Angular 1 (or AngularJS) still gets updates but Angular 2 is well accepted in the community because of its obvious advantages over its older version. The latest stable version is &lt;a href="https://v11.angular.io/guide/updating-to-version-11"&gt;Angular 11&lt;/a&gt;, which was released in November 2020.&lt;/p&gt;

&lt;p&gt;A few big companies that use Angular in 2021 :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft Office&lt;/li&gt;
&lt;li&gt;Deutsche Bank&lt;/li&gt;
&lt;li&gt;Gmail&lt;/li&gt;
&lt;li&gt;Forbes&lt;/li&gt;
&lt;li&gt;PayPal&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;React Js&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;React.js or ReactJS or React is a JavaScript library of UI components, used for creating intuitive user interfaces. This JS library was initially released by Facebook in 2013.&lt;/p&gt;

&lt;p&gt;It is an open-source library maintained by Facebook and hundreds &amp;amp; thousands of individual developers and companies in the community. This library is currently used by all Facebook products, including WhatsApp and Instagram.&lt;/p&gt;

&lt;p&gt;The current stable version is &lt;a href="https://github.com/facebook/react/blob/main/CHANGELOG.md#1702-march-22-2021"&gt;React 17.0.2&lt;/a&gt;, released in October 2020 (with smaller incremental updates since then).&lt;/p&gt;

&lt;p&gt;Here are a few of the top brands that use React.js for the frontend &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;platforms in 2021 :&lt;/li&gt;
&lt;li&gt;Facebook&lt;/li&gt;
&lt;li&gt;Instagram&lt;/li&gt;
&lt;li&gt;WhatsApp&lt;/li&gt;
&lt;li&gt;Yahoo&lt;/li&gt;
&lt;li&gt;New York Times&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Vue Js&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Vue.js is a progressive JavaScript framework, known for its ability to create amazing user interfaces. This framework was initially released in 2014 by Evan You – an ex-employee of Google.&lt;/p&gt;

&lt;p&gt;Even though Vue.js doesn’t have the backing of a huge conglomerate, it is still quite popular and is considered to be one of the top JavaScript frameworks/libraries to create intuitive user interfaces in 2021.&lt;/p&gt;

&lt;p&gt;The current stable version is &lt;a href="https://v3.vuejs.org/"&gt;Vue 3&lt;/a&gt;, released in September 2020 (with some small incremental releases since then).&lt;/p&gt;

&lt;p&gt;Big names that use Vue.js in 2021 are :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Xiaomi&lt;/li&gt;
&lt;li&gt;Grammarly&lt;/li&gt;
&lt;li&gt;Adobe&lt;/li&gt;
&lt;li&gt;Behance&lt;/li&gt;
&lt;li&gt;Reuters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Selecting a frontend framework isn’t easy. There are many things to consider, with various advantages and disadvantages to compare, and several issues to discuss! To help you make your decision, we have prepared a detailed comparison of the best JavaScript frameworks. After reading this article, you’ll understand what options work best for your needs!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1.Popularity ( Market and demand)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Each one of the mentioned technologies have their own purpose in regards to how to approach and handle a specific project. For example, Angular is an extensive front-end framework that lets you develop dynamic single-page web apps, suited for large-scale enterprise projects.&lt;/p&gt;

&lt;p&gt;However, Vue and React are also capable and flexible enough to be used in both enterprise or start-up level projects when developing UI through the use of components.&lt;/p&gt;

&lt;p&gt;The more popular a particular framework is, the easier it will be to get talents, resources, community help, etc. The popularity of a framework depends on a variety of factors, such as :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How frequently does the framework/library get new updates?&lt;/li&gt;
&lt;li&gt;What advantages does the framework/library give over the native JavaScript language?&lt;/li&gt;
&lt;li&gt;Is the framework/library still in demand?&lt;/li&gt;
&lt;li&gt;Does the library/framework make the job easier for developers?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Among all the Web Frameworks, React.js stands at #2 with 35.9% votes, followed by Angular/AngularJS at #3 with 25.1% votes. Vue.js, with 19.1% votes, stands at #7 in the chart.&lt;/p&gt;

&lt;p&gt;Verdict : In terms of popularity, React/React.js/React JS is the winner on all counts among React vs Angular vs Vue in 2021.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2.Community and ecosystem&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;When choosing a framework you want to learn, an active community and development are part of a growing and stable ecosystem. All of the mentioned frameworks are under active development and maintenance while being used by thousands of developers. That means there are people willing to help you out and share their knowledge with you.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Angular Ecosystem&lt;/strong&gt;&lt;br&gt;
Angular is the oldest of the three frameworks, and it has been around since 2010. Being developed and maintained by Google, Angular offers a lot of ready-made components for any new and aspiring UI developers who are looking to start building mobile and web apps. It features a lot of pre-built components from Google’s Material Design visual design language to CSS themes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React Ecosystem&lt;/strong&gt;&lt;br&gt;
Developed by Facebook back in 2013, React is the second oldest framework on our comparison list. Since then it has grown massively in popularity and amassed a big community.&lt;/p&gt;

&lt;p&gt;When compared to Angular and Vue, React may be the winner in terms of overall ecosystem maturity and component availability as well as community. Also, it offers integrations with other platforms and tools like Git, UXPin.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vue Ecosystem&lt;/strong&gt;&lt;br&gt;
Developed in 2014 Vue is the youngest when compared to the other two frameworks, but has grown a lot in popularity. When it comes to data binding, Vue made a lot of things easy for developers. Speeding up mobile and web app development with Vue means using the most popular open-source projects within the ecosystem so you can take advantage of input components.&lt;/p&gt;

&lt;p&gt;An additional metric that you’ll want to consider is GitHub’s Used by badge, which needs to be enabled by the repository author. This shows how many other repositories on GitHub are dependent on that repository. Angular’s GitHub repo shows 1.7 million, React currently shows almost 5.7 million users, while Vue shows over 167,000 for both of its repos combined.&lt;/p&gt;

&lt;p&gt;Quite a difference among the three frameworks, but this is largely due to Vue being the newer framework and doesn’t tell the full picture on overall demand.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;3.Architecture&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;With this basic notion, let’s look at the architecture of these 3 JavaScript frameworks – React vs Vue vs Angular&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Angular&lt;/strong&gt;&lt;br&gt;
Angular, being the oldest one of the lot, has the Model-View-Controller (MVC) architecture. MVC architecture is the classic old way of separating even the most complex UIs into three views – Business Logic, UI Logic, and Input Logic. The execution is simple.&lt;/p&gt;

&lt;p&gt;It is based on MVC which, as discussed, makes it super easy to modify and upgrade individual views without the need for completely re-writing the other views.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React Js&lt;/strong&gt;&lt;br&gt;
React is a UI library and, unlike other frameworks and libraries, it doesn’t ‘enforce’ an architecture pattern.&lt;/p&gt;

&lt;p&gt;A React component is essentially a minimalistic central structure unit – as simple as a label &amp;amp; a button or a bit complex as a user profile or a registration form. It is just a view that caters to your web app’s user interface.&lt;/p&gt;

&lt;p&gt;React.js has a component-based architecture. This just means that the user interface of a web app powered by React is nothing but a combination of loosely bound React elements. When a user interacts with a particular element of the UI, just the state of that particular React component is altered.&lt;/p&gt;

&lt;p&gt;This, right here, is what makes React elements reusable &amp;amp; fully customizable, making it a perfect choice for your web app’s frontend development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vue Js&lt;/strong&gt;&lt;br&gt;
As mentioned earlier, Vue was created by an ex-employee of Google. One of the reasons why this framework is still in the runs for the BEST JS framework is because it contains the best of both worlds – React and Angular.&lt;/p&gt;

&lt;p&gt;Vue.js uses a two-way data binding – a v-model directive. And as Vue.js is focused primarily on the View model, its compatibility with other libraries is just phenomenal. The architecture of Vue.js is designed such that it is incrementally adoptable.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;4.Syntax&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;When it comes to syntax and structuring your code, it’s probably a matter of personal preference. Some developers like to use TypeScript while others stick to JavaScript and there’s really no argument here because syntax doesn’t impact anything in terms of performance.&lt;/p&gt;

&lt;p&gt;And if you really don’t like the way a certain library handles the code in terms of syntax, you should probably not work with that framework on a daily basis.&lt;/p&gt;

&lt;p&gt;So in terms of syntax and structure complexity, Angular will be the most demanding because projects in Angular use TypeScript, the JavaScript superset and it’s something you’ll have to learn additionally.&lt;/p&gt;

&lt;p&gt;As a component-based framework, Vue utilizes single file components and plain JavaScript so you’ll probably find code written in JS only although it offers TypeScript support too.&lt;/p&gt;

&lt;p&gt;Compared to Angular, Vue syntax is the easiest to learn and to grasp for any newcomer dev and UI developer since it doesn’t mix HTML and JavaScript. As mentioned, React is the easiest one to learn both in terms of web and UI development.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;5.Performance&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The performance of a web app depends on the framework or library you use. If you are considering choosing either of these frameworks/libraries for a small project, you can freely choose any of the frameworks I’ve mentioned.&lt;/p&gt;

&lt;p&gt;Things become a bit complicated when the scalability, robustness, and integrability of a JS framework are taken into account. In this React vs Angular vs Vue 2021 comparison, I like to talk about two different aspects when it comes to comparing the performance of these JS libraries and frameworks – DOM and JS Framework Benchmark.&lt;/p&gt;

&lt;p&gt;Angular relies heavily on real DOM for its performance while Vue.js and React function using virtual DOM. Without delving into technical details, virtual DOM saves the trouble of re-rendering/repainting your web app’s UI after every state change. This makes it quicker, especially when multiple component states are involved.&lt;/p&gt;

&lt;p&gt;Having said that, Angular is still a preferred choice of many professional developers to create large-scale SPAs. When it comes to memory requirements and booting time, React &amp;amp; Vue.js show superior results to Angular.&lt;/p&gt;

&lt;p&gt;Angular requires more computational memory and can take up to 150 ms to boot even a basic script.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;6.Migrations&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;As you’re working with your framework of choice, you don’t want to have to worry about a framework update coming along and messing up your code. Though in most cases you won’t encounter many issues from one version to another, it’s important to keep your finger on the pulse because some updates can be more significant and require tweaks to keep things compatible.&lt;/p&gt;

&lt;p&gt;Angular plans major updates every six months. There is also a period of another six months before any major APIs are deprecated, which gives you the time of two release cycles (one year) to make necessary changes, if any.&lt;/p&gt;

&lt;p&gt;When it comes to Angular vs React, Facebook has stated that stability is of utmost importance to them, as huge companies like Twitter and Airbnb use React. Upgrades through versions are generally the easiest in React, with scripts such as react-codemod helping you to migrate.&lt;/p&gt;

&lt;p&gt;In the Migration section of the Vue 3 docs, Vue mentions that much is the same between Vue 2 and Vue 3 while 90% of the API is the same if you are migrating from 1.x to 2. There is a Vue 2 to Vue 1 migration helper tool that works on the console to assess the status of your app.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Which one is the Best ?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;When comparing the three most popular JavaScript frameworks, there is no absolute best when it comes to UI development since all three are under a very active development&lt;/p&gt;

&lt;p&gt;However, each of these libraries has its own benefits and drawbacks., based on many aspects that we’ve covered, you should make your choice based on both the projects you want to work on and the team you’re going to be a part of.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;The most important thing would be to always keep up to date on the newest features and development regardless of which JavaScript framework you choose to dedicate your time to.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>react</category>
      <category>vue</category>
      <category>framework</category>
    </item>
  </channel>
</rss>
