<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kazmi on Medium]]></title>
        <description><![CDATA[Stories by Kazmi on Medium]]></description>
        <link>https://medium.com/@AbidKazmi?source=rss-5ea716055515------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oh1_ldGnZO-bE4O7RBvGMg.png</url>
            <title>Stories by Kazmi on Medium</title>
            <link>https://medium.com/@AbidKazmi?source=rss-5ea716055515------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:04:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AbidKazmi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Top 6 React Libraries of 2023: Boost Your Web Dev Game!]]></title>
            <link>https://medium.com/@AbidKazmi/top-6-react-libraries-of-2023-boost-your-web-dev-game-102689d6d2e9?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/102689d6d2e9</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 12:37:53 GMT</pubDate>
            <atom:updated>2023-08-03T12:37:53.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*9amzZrfc6o59dMd4IuncEg.png" /></figure><p>Web development is constantly evolving and react has been a rockstar in this journey! 🌟 With its flexibility and component-based architecture, it’s a top choice for developers worldwide. Now, in 2023, let’s dive into the 10 best React libraries📚💪.</p><p>Before we embark on our journey through the marvelous world of React libraries, grace us with your presence by clicking on the follow button 🙏.</p><h3>1: Daisy UI — 🌼 for Beautiful UIs!</h3><p>🌈 Daisy UI is a game-changer! With a plethora of customizable components, it simplifies UI development. You’ll breeze through responsive designs using its pre-built elements and tailwind-based utility classes! Saving time⏳ and creating captivating user experiences is a piece of cake! 🍰</p><p>let’s create a card component with daisy that you can see how cool Daisy Ui 🌼 is.</p><pre>&lt;div className=&quot;card w-96 bg-base-100 shadow-xl&quot;&gt;<br>  &lt;figure className=&quot;px-10 pt-10&quot;&gt;<br>    &lt;img src=&quot;/images/stock/photo-1606107557195-0e29a4b5b4aa.jpg&quot; alt=&quot;Shoes&quot; className=&quot;rounded-xl&quot; /&gt;<br>  &lt;/figure&gt;<br>  &lt;div className=&quot;card-body items-center text-center&quot;&gt;<br>    &lt;h2 className=&quot;card-title&quot;&gt;Shoes!&lt;/h2&gt;<br>    &lt;p&gt;If a dog chews shoes whose shoes does he choose?&lt;/p&gt;<br>    &lt;div className=&quot;card-actions&quot;&gt;<br>      &lt;button className=&quot;btn btn-primary&quot;&gt;Buy Now&lt;/button&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*BNl_8LlbO-kyt0M1XUEiLw.jpeg" /></figure><h3>2: React Query — ⚡ Supercharged Data Handling!</h3><p>Managing data fetching and state can be tough, but React Query is here to save the day! ⏰ It optimizes API calls, cuts down on re-renders, and handles caching like a pro! Say goodbye to sluggish apps and hello to seamless user interactions! 🚀</p><h3>3: React-Chartjs— 📊 Data Visualization Made Fun!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2dtCArsTkWPStz5mnhFmw.png" /></figure><p>Numbers and data can sometimes be overwhelming, but fear not, because React Charts are here to save the day! 🎲 With an array of chart types and customization options, presenting data is now an art form! From simple line graphs to mind-blowing dashboards, you’ll impress users with every data visualization! 🎨</p><p><em>Why use React-chartjs:</em></p><p>Raw data can be boring, and making sense of it can be a real challenge. This is where React-Chartjs come to the rescue! They make data visualization engaging, interactive, and dare I say, fun! 🎉</p><ol><li>Visual Appeal: React Charts turn dull numbers into captivating visualizations that are easy to comprehend and analyze. Whether it’s a pie chart, bar graph, or area chart, the aesthetics will make users want to explore the data.</li><li>Interactivity 🧠: With React Charts, you can add interactivity to your data visualizations. Zoom in, pan, or click on elements to reveal more details. Your users will feel like they are in control of the data, making the experience more engaging.</li><li>Responsive : React Charts are responsive by design, ensuring that your data visualizations adapt beautifully to different screen sizes and devices. So, whether your users are on a desktop or a mobile device, they’ll get the best experience.</li><li>Easy Integration 🐥: Thanks to the power of React-Chartjs, integrating charts into your application is a breeze.</li></ol><h3>4: React Spring — 🍃 Animated Delight!</h3><p>🎉 Let your app come alive with React Spring’s enchanting animations! From page transitions to interactive elements, it’s a joy to watch! 🎢 Say goodbye to dull user experiences and hello to animations that’ll leave users wanting more! 🎡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tMWoPUiKJvR0S7MIbpVdg.jpeg" /></figure><h3>5: Formik — 📝 Easier Form Handling!</h3><p>Filling out forms should be a cinch, and Formik makes it so! 🎯 With simplified form validation and state management, you’ll handle even the most complex forms with ease!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*B6aqabQWLCPS8BlEQCA0yQ.jpeg" /></figure><h3>6: React Icons — 🎭 Iconic App Vibes!</h3><p>Last but not least, React Icons to add that extra flair! 🎉 It offers a vast collection of scalable and customizable icons for your UI. Sprinkle some icon magic into your projects and make them stand out! ✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*AaaZbFhdO6knWV3mzM3h9Q.jpeg" /></figure><h3>conclusion:</h3><p>In 2023, React libraries are here to make your web development journey a breeze! From Daisy UI’s beautiful components to React Query’s data prowess and React Charts’ vibrant visuals, these libraries will elevate your apps to the next level! 💻💪 So, let’s embrace these awesome tools and watch our React applications soar high in the dynamic landscape of 2023! Happy coding! 🚀🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102689d6d2e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The React useEffect Hook: Making Magic Happen.]]></title>
            <link>https://medium.com/@AbidKazmi/the-react-useeffect-hook-making-magic-happen-ab64c9396139?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab64c9396139</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 13:36:42 GMT</pubDate>
            <atom:updated>2023-07-28T13:36:42.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*oskclgVpClbO3FiJW3spdg.png" /></figure><p>Hey there, fellow Reactors! Today, we’re diving deep into the enchanting world of the useEffect hook. Buckle up, because we’re going to make some React magic happen, all with a sprinkle of sass and a dash of humor! 🎉</p><h3>The Basics of useEffect:</h3><p>Let’s start with the basics, shall we? The useEffect hook is like a sorcerer’s spellbook for handling side effects in React components. It’s a way for your component to interact with the outside world and perform tasks like fetching data, setting up subscriptions, or cleaning up resources. All without breaking a sweat! 🔮</p><p>The useEffect hook works its magic after React has finished rendering your component. Think of it as the perfect time for your component to roll up its sleeves and say, “Alright, now let’s get to work!”</p><p>Let’s see a code example that how useEffect actually works.</p><pre>import React, { useEffect } from &#39;react&#39;;<br><br>const MyComponent = () =&gt; {<br>  useEffect(() =&gt; {<br>    // Your spellbinding code goes here!<br>    console.log(&quot;I&#39;m casting a spell with useEffect!&quot;);<br>  },[]); // [] is called the dependency array more about this on scroll<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Watch the magic unfold! ✨&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this magical incantation, we’re introducing you to the mighty <em>useEffect </em>hook. It&#39;s like a powerful wizard that lets your React component interact with the outside world. But don&#39;t worry, it&#39;s not as intimidating as it sounds!</p><p>Within the <em>useEffect </em>spellbook, you&#39;ll find a function. The moment React finishes rendering your component, this function leaps into action. It&#39;s the perfect time for your component to perform tasks that require a bit of extra magic. ✨</p><p>The code inside the <em>useEffect </em>function is where the real sorcery happens. You can perform all sorts of tricks here, like fetching data, setting up subscriptions, or even just casting a console.log spell, as shown here: &quot;I&#39;m casting a spell with useEffect!&quot;.</p><p>But wait! There’s a peculiar charm at the end of this <em>useEffect </em>invocation[]. That&#39;s called the dependency array, and it&#39;s what makes this magic a bit more controlled.</p><p>In the realm of React, the <em>dependency array </em>is like a mystical ward that instructs the spell when to be recast. Here, we&#39;ve left it empty, which means the spell is cast only once, right after your component appears/renders for the first time. 🧙‍♂️</p><p>🙄 Now, you might be wondering, “What happens when we change the dependency array or put some variables inside it?” Ah, that’s where the story gets even more intriguing! By including specific variables in the <em>dependency array,</em> you can instruct the spell to recast whenever any of those variables change.</p><p>So, let’s see a code Example.</p><pre>import React, { useEffect, useState} from &#39;react&#39;;<br>const MyComponent = () =&gt; {<br>const [count,setCount] = useState(0)<br>  useEffect(() =&gt; {<br>    console.log(&quot;I&#39;m casting a spell with useEffect!&quot;);<br>  },[count]); // we passed the count variable inside the dependency array<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Watch the magic unfold! ✨&lt;/p&gt;<br>      &lt;button onClick={()=&gt; setCount(count +1)}&gt;➕&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Now whenever you click on the ➕ button the count changes and when the count changes the useEffect will run again because we have passed the count variable in the dependency array.</p><p><em>Let’s do some cool 🍚 stuff with useEffect:</em></p><p>Let’s create a React component that fetches blogs data for a specific category using the<em> useState</em> hook. Whenever the category state changes, we&#39;ll trigger a fetch to get the blogs of that category.</p><p>To keep things simple, we’ll use the <em>jsonplaceholder</em> API as a mock API to simulate fetching blog data.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>const BlogList = () =&gt; {<br>  const [category, setCategory] = useState(&#39;technology&#39;);<br>  const [blogs, setBlogs] = useState([]);<br><br>  useEffect(() =&gt; {<br>    // Function to fetch blogs data for the selected category<br>    const fetchBlogs = async () =&gt; {<br>      try {<br>        const response = await fetch(<br>          `https://jsonplaceholder.typicode.com/posts?category=${category}`<br>        );<br>        const data = await response.json();<br>        setBlogs(data);<br>      } catch (error) {<br>        console.error(&#39;Error fetching blogs:&#39;, error);<br>      }<br>    };<br><br>    fetchBlogs(); // Fetch blogs when the category state changes<br>  }, [category]); // we have passed the category variable bocoz we want to<br>                  // refetch the bolgs whenever the category changes<br><br>  const handleCategoryChange = (newCategory) =&gt; {<br>    setCategory(newCategory);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Blog List&lt;/h1&gt;<br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;categorySelect&quot;&gt;Select a category: &lt;/label&gt;<br>        &lt;select<br>          id=&quot;categorySelect&quot;<br>          value={category}<br>          onChange={(e) =&gt; handleCategoryChange(e.target.value)}<br>        &gt;<br>          &lt;option value=&quot;technology&quot;&gt;Technology&lt;/option&gt;<br>          &lt;option value=&quot;lifestyle&quot;&gt;Lifestyle&lt;/option&gt;<br>          &lt;option value=&quot;travel&quot;&gt;Travel&lt;/option&gt;<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br>      &lt;ul&gt;<br>        {blogs.map((blog) =&gt; (<br>          &lt;li key={blog.id}&gt;{blog.title}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default BlogList;</pre><p>In this code example whenever we change category the useEffect hook will be recalled and it will refetch the blogs for that category.</p><p>It’s like saying, “Hey, useEffect! Keep an eye 👁‍🗨 on these variables, and whenever any of them change, cast the spell again!” This way, your component stays in sync with the ever-changing world around it.</p><p>Now that you have seen 👀 some basic useEffect examples, let’s do something more advance 😁.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>const UsersComponent = () =&gt; {<br>  // State to manage the array of users<br>  const [users, setUsers] = useState([]);<br><br>  // Load users from localStorage on component initial render<br>  useEffect(() =&gt; {<br>    const storedUsers = JSON.parse(localStorage.getItem(&#39;users&#39;)) || [];<br>    setUsers(storedUsers);<br>  }, []);<br><br>  // Save users to localStorage whenever the users array changes<br>  useEffect(() =&gt; {<br>    localStorage.setItem(&#39;users&#39;, JSON.stringify(users));<br>  }, [users]);<br><br>  // Function to add a new user to the array and localStorage<br>  const addUser = (newUser) =&gt; {<br>    setUsers([...users, newUser]);<br>  };<br><br>  // Function to delete a user from the array and localStorage<br>  const deleteUser = (userId) =&gt; {<br>    const updatedUsers = users.filter((user) =&gt; user.id !== userId);<br>    setUsers(updatedUsers);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Users List&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {users.map((user) =&gt; (<br>          &lt;li key={user.id}&gt;<br>            {user.name}{&#39; &#39;}<br>            &lt;button onClick={() =&gt; deleteUser(user.id)}&gt;Delete&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;button<br>        onClick={() =&gt;<br>          addUser({<br>            id: Date.now(),<br>            name: `User ${users.length + 1}`,<br>          })<br>        }<br>      &gt;<br>        Add User<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UsersComponent;</pre><p>We have implemented two essential functions within our system: “<strong>addUser</strong>” facilitates the addition of a new user to the array, while “<strong>deleteUser</strong>” ensures the removal of a user from both the array and the corresponding localStorage.</p><p>Furthermore, when a user initiates a deletion operation, it triggers a change in the users’ state, subsequently prompting the useEffect function to execute and save the current users data to the local storage.</p><p>To observe the functionality in action, kindly click the “Add User” button, which will promptly append a new user to the existing list. Similarly, selecting the “Delete” button adjacent to each user will effectively eliminate the corresponding user from the list as well as the localStorage.</p><p>So, as you can see, the <em>useEffect </em>hook is a powerful ally, helping you bring magic to your React components without breaking a sweat. So go forth, cast your spells, and let the magic unfold! 🌟✨</p><p>Happy coding journey. 💕</p><p>Don’t forget to 👏 and follow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab64c9396139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Use Next.js Instead of React for Full Stack Applications.]]></title>
            <link>https://medium.com/@AbidKazmi/why-use-next-js-instead-of-react-for-full-stack-applications-bc280134f976?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc280134f976</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 12:11:46 GMT</pubDate>
            <atom:updated>2023-07-13T08:26:28.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V02VEtdGLWlC0fWOyaD6g.jpeg" /><figcaption>Nextjs</figcaption></figure><p>When it comes to building full stack applications, React has been the go-to JavaScript library for many developers. However, there’s a powerful framework called Next.js that adds significant value and efficiency to the development process. In this blog post, we’ll explore why Next.js is a smart choice over React for developing full stack applications. We’ll discuss its key features and provide code examples to illustrate its advantages.</p><h4>1: Server Side Rendering (SSR):</h4><p>One of the main reasons to choose Next.js for full stack applications is its built-in server-side rendering capabilities. React is primarily focused on client-side rendering, which means that the initial page load is slower and search engine optimization (SEO) can be challenging. With Next.js, you can easily implement server-side rendering, allowing your pages to be rendered on the server and sent as HTML to the client. This improves page load times and enhances SEO, resulting in better performance and discoverability.</p><p>Lets Look at the following code.</p><pre>import React from &#39;react&#39;;<br>import ProductModel from &#39;@models/product&#39;;<br>import { connectDB } from &#39;@utils/connect&#39;<br><br>function Home({ products}) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to Next.js!&lt;/h1&gt;<br>       &lt;ul&gt;<br>         {products.map((product) =&gt; (<br>          &lt;li key={product._id}&gt;{product.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export async function getServerSideProps() {<br>  <br>  connectDB() // first connect to database<br><br>  const products = await ProductModel.find();<br><br>  return {<br>    props: {<br>      products: JSON.stringify(products),<br>      //  we can get these products in props and use in our page<br>    },<br>  };<br>}<br><br>export default Home;</pre><p>Look How simple is that. You do not need to use fetch or something else. that is 🆒.</p><h3>2.API Routes:</h3><p>Next.js simplifies the process of creating serverless API endpoints within your application. It provides an intuitive way to define API routes, allowing you to handle backend functionality without the need for a separate server. This makes it easier to develop and maintain full stack applications by keeping both the frontend and backend code in a single codebase.</p><p>lets look at the following code example that how can you do CRUD Operations in Next js API routes.</p><p><strong><em>1: GET Request</em></strong></p><pre>import ProductModel from &quot;@/models/product&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br><br>export async function GET(request){<br>      // function name should be GET<br>    try {<br>        const products = await ProductModel.find()<br>        return NextResponse.json( products, { status:200 })<br>    } catch (error) {<br>        return NextResponse.json({ message : error.message },{ status:400 })<br>    }<br>}<br></pre><p>Look How Cool is this. You just need to name the function of the Request. then Next js will handle all the other stuff by itself.</p><p><strong><em>2 : POST Request :</em></strong></p><pre>import ProductModel from &quot;@/models/product&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br><br>export async function POST(request){<br>    // function name should be POST<br>    const {name,price,description} =  await request.json()<br>    try {<br>        const product = new ProductModel({<br>          name,<br>          price,<br>          description<br>        })<br>         await product.save()<br><br>        return NextResponse.json( &#39;product created successfully&#39;, { status:200 })<br>    } catch (error) {<br>        return NextResponse.json({ message : error.message },{ status:400 })<br>    }<br>}</pre><p>Same thing isn’t it. You just need to Name the function POST to send post request.</p><p><strong><em>3: DELETE Request:</em></strong></p><pre>import connectDb from &quot;@/lib/connectDb&quot;;<br>import ProductModel from &quot;@/models/product&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br><br>export async function DELETE(request,{ params }) {<br>    try {<br>      await connectDb()<br>      await ProductModel.findByIdAndDelete(params.id)<br>      return NextResponse.json(&quot; user deleted successfully&quot;);<br>  <br>    } catch (error) {<br>      return NextResponse.json({ message: error.message });<br>    }<br>  }</pre><p><strong><em>4: PUT Request:</em></strong></p><pre><br>import connectDb from &quot;@/lib/connectDb&quot;;<br>import ProductModel from &quot;@/models/product&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br><br>export async function PUT(request,{ params}){<br>    try {<br>        await connectDb()<br>        const { name, price, description} = await  request.json()<br><br>        const productDataToUpdate = {<br>            name,<br>            price,<br>            description<br>        }<br><br>        const updatedProduct =  await ProductModel.findByIdAndUpdate(params.id , productDataToUpdate) <br>      return NextResponse.json(&quot; user updated successfully&quot;,updatedProduct);<br>        <br>    } catch (error) {<br>      return NextResponse.json({ message: error.message });<br>    }<br>}</pre><p>And that is it for API Routes.</p><h3>3: Authentication (With NextAuth.js):</h3><p>NextAuth.js is an open-source authentication library designed specifically for Next.js applications. It simplifies the process of implementing various authentication providers such as OAuth, JWT, database adapters, and more. With NextAuth.js, you can effortlessly authenticate users using popular providers like Google, GitHub, Facebook, or even custom authentication schemes.</p><p>One of the significant advantages of NextAuth.js is its seamless integration with Next.js. It provides built-in support for server-side rendering (SSR) and API routes, allowing you to handle authentication logic on the server and securely protect your API endpoints. This combination of Next.js and NextAuth.js ensures that the authentication process is fast, efficient, and optimized for performance.</p><p>Let&#39;s see that How you can integrate NextAuth in Next.js Application.</p><p><strong><em>SignIn with google and other applications or Providers in NextAuth:</em></strong></p><pre>import GoogleProvider from &quot;next-auth/providers/google&quot;;<br><br><br>export const AuthOptions = {<br>  providers: [<br>  GoogleProvider({<br>    clientId: process.env.GOOGLE_CLIENT_ID,<br>    clientSecret: process.env.GOOGLE_CLIENT_SECRET<br>  })<br>]<br>};</pre><p>And your SignIn with Google Completes here. and same goes for GithubProvider, FaceBookProvider, TwitterProvider, InstagramProvider and etc. You just need to change the Provider Name and get the clientId and the clientSecret from your favorite auth application.</p><p><strong><em>SignIn with Credentials:</em></strong></p><pre>import connectDb from &quot;@/lib/connectDb&quot;;<br>import User from &quot;@/models/user&quot;;<br>import CredentialsProvider from &quot;next-auth/providers/credentials&quot;;<br>import bcrypt from &quot;bcrypt&quot;;<br>import { MongoDBAdapter } from &quot;@auth/mongodb-adapter&quot;;<br>import clientPromise from &quot;./mongoAdapter&quot;;<br><br><br>export const AuthOptions = {<br>  adapter:MongoDBAdapter(clientPromisae),<br>  providers: [<br>    GoogleProvider({<br><br>    }),<br>    CredentialsProvider({<br>      name: &quot;Credentials&quot;,<br>      credentials: {<br>        email: {<br>          label: &quot;Email&quot;,<br>          placeholder: &quot;Enter your Email&quot;,<br>          type: &quot;email&quot;,<br>        },<br>        password: {<br>          label: &quot;Password&quot;,<br>          placeholder: &quot;*******&quot;,<br>          type: &quot;password&quot;,<br>        },<br>      },<br>      async authorize (credentials) {<br>        await connectDb();<br>        const { email, password } = credentials;<br>        const user = await User.findOne({ email });<br><br>        if (!user) {<br>          throw new Error(&quot;User with this email does not exist&quot;);<br>        }<br>        const isPasswordCorrect = await bcrypt.compare(password, user.password);<br><br>        if (!isPasswordCorrect) {<br>          throw new Error(&quot;Invalid credentials&quot;);<br>        }<br>        if (user &amp;&amp; isPasswordCorrect) {<br>          return user;<br>        } else {<br>          return null;<br>        }<br>      },<br>    }),<br>  ],<br>  <br>  secret:process.env.NEXT_AUTH_SECRET,<br>  session:{<br>    strategy:&#39;jwt&#39;<br>  }<br>};</pre><p>And that’s it for Authentications with NextAuth.js.</p><h3>Static Site Generation (SSG):</h3><p>In addition to server-side rendering, Next.js supports static site generation. It allows you to pre-render pages at build time, which can be beneficial for content-heavy websites. By generating static HTML files, you can deliver fast-loading pages with reduced server load, providing an excellent user experience.</p><p>let’s see how we can implement static site generation (SSG) in Next.js</p><pre>// pages/index.js<br><br>import React from &#39;react&#39;;<br><br>export default function Home({ products }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Dynamic Content Fetched at Build Time&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {products.map((product) =&gt; (<br>          &lt;li key={product.id}&gt;{product.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export async function getStaticProps() {<br>  // Fetch data from an API or any data source<br>  const response = await fetch(&#39;/api/products&#39;);<br>  const products = await response.json();<br><br>  return {<br>    props: {<br>      products,<br>    },<br>  };<br>}</pre><p>During the build process, Next.js will call the getStaticProps function, fetch the data from the specified API endpoint (/api/products in this case), and pass it as props to the Home component. This way, the content will be pre-rendered into static HTML files.</p><p>When a user visits the website, they will be served the pre-rendered static HTML file, resulting in faster page load times. Note that subsequent requests to the same page will be served directly from the static HTML file, without re-fetching the data, unless you configure Next.js to revalidate and regenerate the HTML file at a certain interval.</p><p>How Cool Experience is that. isn’t it. if yes then 👏 .</p><h3>Lasting:</h3><p>Next.js offers a powerful set of features that make it a superior choice for building full stack applications compared to using React alone. Its server-side rendering, automatic code splitting, API routes, and static site generation capabilities enable developers to create performant and SEO-friendly applications more efficiently. By leveraging Next.js, you can enjoy the benefits of both React and a robust full stack framework, making your development process smoother and more productive.</p><p>Start exploring Next.js for your next full stack project, and experience the ease and efficiency it brings to your application development journey. Happy coding!</p><p>👏👏👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc280134f976" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All React hooks in one short.]]></title>
            <link>https://medium.com/@AbidKazmi/all-react-hooks-in-one-short-4b0ed4b5a6e4?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b0ed4b5a6e4</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 11:31:21 GMT</pubDate>
            <atom:updated>2023-07-28T13:49:38.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ow_CzsxTrJXe4_APCiEwUQ.png" /></figure><p>React hooks are a powerful feature in React that allow you to add state and other features to functional components. They were introduced in React 16.8 and have since become an integral part of React development. In this blog, we’ll explore some of the most commonly used React hooks and provide easy-to-understand examples.</p><h3>1: useState hook</h3><p>The useState hook allows you to add state to a functional component. It takes an initial value as an argument and returns an array with two elements: the current state value and a function to update it.</p><p>Here’s an example of how to use useState to add a counter to a functional component:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  const increment= () =&gt; {<br>    setCount(count + 1);<br>  }<br>const decrement = () =&gt; {<br>    setCount(count - 1);<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we start with a count of 0 and update it every time the “Increment” and ‘’decrement’’ button is clicked.</p><h3>2: useEffect hook</h3><p>The useEffect hook allows you to perform side effects in a functional component. Side effects include things like fetching data from an API, updating the DOM, or subscribing to an event.</p><p>Here’s an example of how to use useEffect to fetch data from an API:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function DataFetcher() {<br>  const [data, setData] = useState([]);<br><br>  useEffect(() =&gt; {<br>    fetch(&#39;https://api.example.com/data&#39;)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; setData(data));<br>  }, []);<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map(item =&gt; (<br>        &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>In this example, we fetch data from an API and update the component’s state with it using the setData function.</p><h3>3: useContext hook</h3><p>The useContext hook allows you to access a context object in a functional component. Context is a way to pass data down the component tree without having to pass props manually.</p><p>Here’s an example of how to use useContext to access a theme context:</p><pre>import React, { useContext } from &#39;react&#39;;<br><br>const ThemeContext = React.createContext(&#39;light&#39;);<br><br>function ThemeButton() {<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;button style={{ background: theme === &#39;dark&#39; ? &#39;black&#39; : &#39;white&#39;, color: theme === &#39;dark&#39; ? &#39;white&#39; : &#39;black&#39; }}&gt;<br>      Toggle Theme<br>    &lt;/button&gt;<br>  );<br>}</pre><p>In this example, we create a theme context with a default value of “light” and use the useContext hook to access it in the ThemeButton component.</p><h3>4: useReducer hook</h3><p>The useReducer hook allows you to manage complex state in a functional component. It’s similar to the useState hook, but instead of a simple value, it takes a reducer function and an initial state.</p><p>Here’s an example of how to use useReducer to manage a shopping cart:</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>function cartReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;add&#39;:<br>      return [...state, action.payload];<br>    case &#39;remove&#39;:<br>      return state.filter(item =&gt; item.id !== action.payload.id);<br>    default:<br>      return state;<br>  }<br>}<br><br>function ShoppingCart() {<br>  const [cart, dispatch] = useReducer(cartReducer, []);<br><br>  const addItem = (item) =&gt; {<br>    dispatch({ type: &#39;add&#39;, payload: item });<br>  }<br><br>  const removeItem = (item) =&gt; {<br>    dispatch({ type: &#39;remove&#39;, payload: item });<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Shopping Cart&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {cart.map(item =&gt; (<br>          &lt;li key={item.id}&gt;<br>            {item.name} - ${item.price}<br>            &lt;button onClick={() =&gt; removeItem(item)}&gt;Remove&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;button onClick={() =&gt; addItem({ id: 1, name: &#39;Item 1&#39;, price: 9.99 })}&gt;Add Item&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a cartReducer function that takes a state and an action and returns a new state based on the action type. We then use the useReducer hook to manage the cart state with the cartReducer function.</p><p>We also define two functions, addItem and removeItem, that dispatch actions to the cartReducer to add or remove items from the cart state.</p><p>Finally, we render the shopping cart with the cart items and buttons to add or remove items. When the buttons are clicked, the addItem or removeItem functions are called to update the cart state using the dispatch function returned by the useReducer hook.</p><h3>5: useCallback hook</h3><p>The useCallback hook allows you to memoize a function so that it’s only re-created when its dependencies change. This can help improve performance by preventing unnecessary re-renders.</p><p>Here’s an example of how to use useCallback to memoize a function:</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>function SearchBar({ onSearch }) {<br>  const [query, setQuery] = useState(&#39;&#39;);<br><br>  const handleQueryChange = useCallback(event =&gt; {<br>    setQuery(event.target.value);<br>    onSearch(event.target.value);<br>  }, [onSearch]);<br><br>  return (<br>    &lt;input type=&quot;text&quot; value={query} onChange={handleQueryChange} /&gt;<br>  );<br>}</pre><p>In this example, we define a SearchBar component that takes an onSearch prop function. We use the useCallback hook to memoize the handleQueryChange function so that it’s only re-created when the onSearch function changes.</p><h3>6: useMemo hook</h3><p>The useMemo hook allows you to memoize a value so that it’s only re-computed when its dependencies change. This can help improve performance by preventing unnecessary re-computations.</p><p>Here’s an example of how to use useMemo to memoize a calculated value:</p><pre>import React, { useState, useMemo } from &#39;react&#39;;<br><br>function ExpensiveCalculation({ a, b }) {<br>  const result = useMemo(() =&gt; {<br>    console.log(&#39;Calculating...&#39;);<br>    return a * b;<br>  }, [a, b]);<br><br>  return &lt;p&gt;Result: {result}&lt;/p&gt;;<br>}</pre><p>In this example, we define an ExpensiveCalculation component that takes two props, a and b. We use the useMemo hook to memoize the result of the calculation so that it’s only re-computed when a or b changes.</p><h3>7: useRef hook</h3><p>The useRef hook allows you to create a mutable ref object that persists for the lifetime of the component. You can use it to store and access values that don’t trigger a re-render.</p><p>Here’s an example of how to use useRef to access the value of an input element:</p><pre>import React, { useRef } from &#39;react&#39;;<br><br>function InputWithFocus() {<br>  const inputRef = useRef();<br><br>  const handleClick = () =&gt; {<br>    inputRef.current.focus();<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; ref={inputRef} /&gt;<br>      &lt;button onClick={handleClick}&gt;Focus Input&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define an InputWithFocus component that creates a ref object with the useRef hook and attaches it to the input element. We use the ref object to focus the input when the “Focus Input” button is clicked.</p><h3>8: useLayoutEffect hook</h3><p>The useLayoutEffect hook is similar to useEffect, but it’s executed synchronously after all DOM mutations. This makes it useful for manipulating the DOM immediately after a component is rendered.</p><p>Here’s an example of how to use useLayoutEffect to measure the size of an element:</p><pre>import React, { useState, useLayoutEffect, useRef } from &#39;react&#39;;<br><br>function ResizableBox() {<br>  const [width, setWidth] = useState(100);<br>  const [height, setHeight] = useState(100);<br>  const boxRef = useRef(null);<br><br>  useLayoutEffect(() =&gt; {<br>    const handleResize = () =&gt; {<br>      setWidth(boxRef.current.clientWidth);<br>      setHeight(boxRef.current.clientHeight);<br>    };<br><br>    handleResize();<br><br>    window.addEventListener(&#39;resize&#39;, handleResize);<br>    return () =&gt; window.removeEventListener(&#39;resize&#39;, handleResize);<br>  }, []);<br><br>  return (<br>    &lt;div ref={boxRef} style={{ width: &#39;50%&#39;, height: &#39;50%&#39;, backgroundColor: &#39;red&#39; }}&gt;<br>      &lt;p&gt;Width: {width}px&lt;/p&gt;<br>      &lt;p&gt;Height: {height}px&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a ResizableBox component that uses the useLayoutEffect hook to measure the size of a div element. We then use the size values to render the width and height of the box. The hook also adds and removes a resize event listener to update the size values when the window is resized.</p><h3>9: useDebugValue hook</h3><p>useDebugValue is a hook that allows you to display custom debugging information for custom hooks in the React DevTools. This can be useful for debugging hooks and understanding what&#39;s happening behind the scenes.</p><p>Here’s an example of how to use useDebugValue:</p><pre>import { useState, useEffect, useDebugValue } from &#39;react&#39;;<br><br>function useFetch(url) {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    fetch(url)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; setData(data));<br>  }, [url]);<br><br>  useDebugValue(data ? `Data loaded: ${data.length} items` : &#39;Loading...&#39;);<br><br>  return data;<br>}</pre><p>In this example, we define a custom hook called useFetch that fetches data from a URL and returns it. We use the useDebugValue hook to display a custom debugging message in the React DevTools. If the data is loaded, we display a message that includes the number of items in the data. If the data is still loading, we display a message that says &quot;Loading...&quot;.</p><p>When you use the useFetch hook in a component, the custom debugging message will be displayed in the React DevTools. This can help you understand what&#39;s happening behind the scenes and debug any issues that might arise.</p><p>Note that the useDebugValue hook should only be used for debugging purposes and should not affect the behavior of your custom hook. It&#39;s a great tool to have in your debugging toolbox when working with custom hooks.</p><h3>10: useImperativeHandle hook</h3><p>The useImperativeHandle hook allows you to customize the instance value that is exposed to parent components when using ref. This can be useful when you need to provide a certain interface to parent components, but you don&#39;t want to expose all of the internal implementation details of a child component.</p><p>Here’s an example of how to use useImperativeHandle:</p><pre>import React, { useRef, useImperativeHandle } from &#39;react&#39;;<br><br>const Input = React.forwardRef((props, ref) =&gt; {<br>  const inputRef = useRef();<br><br>  useImperativeHandle(ref, () =&gt; ({<br>    focus: () =&gt; {<br>      inputRef.current.focus();<br>    },<br>    value: inputRef.current.value<br>  }));<br><br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      ref={inputRef}<br>      placeholder={props.placeholder}<br>    /&gt;<br>  );<br>});<br><br>function App() {<br>  const inputRef = useRef();<br><br>  const handleClick = () =&gt; {<br>    inputRef.current.focus();<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;Input ref={inputRef} placeholder=&quot;Type here&quot; /&gt;<br>      &lt;button onClick={handleClick}&gt;Focus input&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a custom Input component that uses useImperativeHandle to expose a focus method and a value property to parent components when using ref. The useImperativeHandle hook takes two arguments: the ref object and a callback function that returns an object with the properties and methods that should be exposed to parent components.</p><p>In the App component, we use the Input component and pass a ref object to it. We also define a handleClick function that calls the focus method of the inputRef object when a button is clicked.</p><p>When you run this code, you’ll see an input field with a placeholder text and a button that says “Focus input”. When you click the button, the focus method of the inputRef object is called, and the input field is focused.</p><p>In summary, the useImperativeHandle hook allows you to customize the instance value that is exposed to parent components when using ref. This can be useful when you need to provide a certain interface to parent components but don&#39;t want to expose all of the internal implementation details of a child component.</p><h3>Summary</h3><ol><li>“With these powerful React hooks in your toolkit, you can take your web development to the next level and build more efficient and effective applications than ever before.”</li><li>“From managing state with useReducer to optimizing performance with useMemo and useCallback, these React hooks are a game-changer for developers.&quot;</li><li>“Whether you’re a seasoned React developer or just starting out, these hooks can help you streamline your code, improve performance, and enhance the user experience.</li><li>“By utilizing the full potential of React hooks such as useDebugValue and useImperativeHandle, you can optimize your code and make it more maintainable and extensible.&quot;</li><li>“In summary, React hooks are a powerful tool that every developer should have in their arsenal. By incorporating these hooks into your projects, you can create better, faster, and more responsive web applications.”</li></ol><h3>If you like it then don’t forget to like and follow.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b0ed4b5a6e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All you need to know about React useReducer hook.]]></title>
            <link>https://medium.com/@AbidKazmi/all-you-need-about-react-usereducer-hook-56f7183312df?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/56f7183312df</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 11:02:58 GMT</pubDate>
            <atom:updated>2023-08-03T18:11:36.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*bScXowslIeY6loPCIVgJlA.png" /></figure><p>One of the most commonly used hooks in React is the useReducer hook, which allows developers to manage state in a more predictable and controlled way. In this blog post, we&#39;ll explore the useReducer hook in detail, and provide three unique examples of how it can be used.</p><p>What is the useReducer Hook?</p><p>The useReducer hook is a function in React that allows you to manage state in a more predictable way. It works similarly to the useState hook, but with a few key differences. Instead of managing state with a single value, you can manage state with a more complex data structure, such as an array or an object. The useReducer hook also provides a way to update state using a reducer function, which takes in the current state and an action, and returns a new state.</p><h3>Example 1: Managing a Todo List</h3><p>One common use case for the useReducer hook is managing a todo list. Let&#39;s say we have an array of todo items, and we want to be able to add new items to the list, mark items as complete, and remove items from the list. We can use the useReducer hook to manage the state of our todo list, and update it based on user actions.</p><p>Here’s an example implementation:</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>function todoReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;ADD_TODO&#39;:<br>      return [...state, { text: action.text, completed: false }];<br>    case &#39;TOGGLE_TODO&#39;:<br>      return state.map((todo, index) =&gt;<br>        index === action.index ? { ...todo, completed: !todo.completed } : todo<br>      );<br>    case &#39;REMOVE_TODO&#39;:<br>      return state.filter((todo, index) =&gt; index !== action.index);<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>function TodoList() {<br>  const [todos, dispatch] = useReducer(todoReducer, []);<br><br>  function handleAddTodo() {<br>    const text = prompt(&#39;Enter new todo:&#39;);<br>    dispatch({ type: &#39;ADD_TODO&#39;, text });<br>  }<br><br>  function handleToggleTodo(index) {<br>    dispatch({ type: &#39;TOGGLE_TODO&#39;, index });<br>  }<br><br>  function handleRemoveTodo(index) {<br>    dispatch({ type: &#39;REMOVE_TODO&#39;, index });<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleAddTodo}&gt;Add Todo&lt;/button&gt;<br>      &lt;ul&gt;<br>        {todos.map((todo, index) =&gt; (<br>          &lt;li<br>            key={index}<br>            style={{ textDecoration: todo.completed ? &#39;line-through&#39; : &#39;none&#39; }}<br>            onClick={() =&gt; handleToggleTodo(index)}<br>          &gt;<br>            {todo.text}<br>            &lt;button onClick={() =&gt; handleRemoveTodo(index)}&gt;X&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a todoReducer function that takes in the current state and an action, and returns a new state based on the action. We then use the useReducer hook to manage the state of our todo list, and define three functions to handle adding, toggling, and removing todos. Finally, we render our todo list and pass in the appropriate event handlers to handle user actions.</p><h3>Example 2: Filtering a List</h3><p>Another useful feature of the useReducer hook is the ability to filter a list based on user input. Let&#39;s say we have an array of items and we want to be able to filter the list based on a user-provided search term. We can use the useReducer hook to manage the state of our list and filter it based on user input.</p><p>Here is an example implementation:</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>function itemReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;SET_ITEMS&#39;:<br>      return action.items;<br>    case &#39;FILTER_ITEMS&#39;:<br>      return state.filter(item =&gt;<br>        item.name.toLowerCase().includes(action.searchTerm.toLowerCase())<br>      );<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>function ItemList({ items }) {<br>  const [filteredItems, dispatch] = useReducer(itemReducer, items);<br><br>  function handleSearchChange(event) {<br>    const searchTerm = event.target.value;<br>    dispatch({ type: &#39;FILTER_ITEMS&#39;, searchTerm });<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; placeholder=&quot;Search...&quot; onChange={handleSearchChange} /&gt;<br>      &lt;ul&gt;<br>        {filteredItems.map(item =&gt; (<br>          &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define an itemReducer function that takes in the current state and an action, and returns a new state based on the action. We then use the useReducer hook to manage the state of our item list, and define a function to handle changes to the search input. Finally, we render our filtered item list and pass in the appropriate event handler to update the state based on user input.</p><p>Example 3: Managing a Counter</p><p>The useReducer hook can also be used to manage the state of a simple counter. Let&#39;s say we have a button that increments a counter each time it&#39;s clicked, and we want to display the current count on the screen. We can use the useReducer hook to manage the state of our counter, and update it based on user actions.</p><p>Here’s an example implementation:</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>function counterReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return state + 1;<br>    case &#39;DECREMENT&#39;:<br>      return state - 1;<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>function Counter() {<br>  const [count, dispatch] = useReducer(counterReducer, 0);<br><br>  function handleIncrement() {<br>    dispatch({ type: &#39;INCREMENT&#39; });<br>  }<br><br>  function handleDecrement() {<br>    dispatch({ type: &#39;DECREMENT&#39; });<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{count}&lt;/h1&gt;<br>      &lt;button onClick={handleIncrement}&gt;+&lt;/button&gt;<br>      &lt;button onClick={handleDecrement}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a counterReducer function that takes in the current state and an action, and returns a new state based on the action. We then use the useReducer hook to manage the state of our counter, and define two functions to handle incrementing and decrementing the counter. Finally, we render the current count and pass in the appropriate event handlers to update the state based on user actions.</p><h3>Conclusion</h3><p>In this blog post, we’ve explored the useReducer hook in React and provided three unique examples of how it can be used. By using the useReducer hook, developers can manage state in a more predictable and controlled way, and build more complex and dynamic user interfaces. Whether you&#39;re managing a todo list, filtering a list, or managing a counter, the useReducer hook is a powerful tool for managing state in React.</p><h4>If you found this blog post helpful or informative, please consider sharing it with your friends and colleagues who may also benefit from learning about the useReducer hook in React. Thank you for reading!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56f7183312df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All JavaScript you Need for React.]]></title>
            <link>https://medium.com/@AbidKazmi/all-javascript-you-need-for-react-6d6a5706ec00?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d6a5706ec00</guid>
            <category><![CDATA[javascript-array-methods]]></category>
            <category><![CDATA[javascript-concepts]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 16:01:47 GMT</pubDate>
            <atom:updated>2023-03-30T16:01:47.107Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>JavaScript </strong>is an essential programming language for front-end web development. It provides the necessary interactivity, dynamic content, and user experience that makes web applications stand out. As such, learning JavaScript is a crucial step in becoming a web developer, and it’s even more important if you’re interested in ReactJS, one of the most popular JavaScript libraries for building user interfaces.</p><p><strong>ReactJS </strong>is a powerful library that makes it easier to build complex user interfaces by breaking them down into smaller, reusable components. However, it is built on top of JavaScript, and relies heavily on many of its core concepts. By mastering JavaScript first, you’ll be well-prepared to use ReactJS to its fullest potential.</p><p>In this Article we will discuss some key JavaScript concepts that are foundational to ReactJS development:</p><h3>1: Variables and Data Types</h3><p>In JavaScript, variables are used to store data that can be used throughout your code. There are several data types in JavaScript, including strings, numbers, booleans, null, and undefined. Understanding these data types is essential when working with ReactJS.</p><p>Example:</p><pre>let myName = &quot;John&quot;;<br>let age = 25;<br>let isMale = true;<br>let myArray = [1, 2, 3];</pre><h3>2: Functions:</h3><p>Functions are reusable blocks of code that perform a specific task. They can be called and used multiple times throughout your code. Functions can also accept parameters, which allow you to pass data into the function.</p><p>example:</p><pre>function sayHello(name) {<br>  console.log(&quot;Hello, &quot; + name + &quot;!&quot;);<br>}<br><br>sayHello(&quot;John&quot;); // outputs &quot;Hello, John!&quot; to the console</pre><h3>3: Objects</h3><p>Objects are a way to store and organize data in JavaScript. They consist of key-value pairs, where the key is a string and the value can be any data type.</p><p>example:</p><pre>let myObject = {<br>  name: &quot;John&quot;,<br>  age: 25,<br>  isMale: true<br>};<br><br>console.log(myObject.name); // outputs &quot;John&quot; to the console</pre><h3>4: Arrays:</h3><p>Arrays are a way to store a collection of data in JavaScript. They can hold any data type, including other arrays and objects.</p><p>example:</p><pre>let myArray = [1, 2, 3, &quot;four&quot;, true];<br>console.log(myArray[3]); // outputs &quot;four&quot; to the console</pre><h3>5: Conditional Statements</h3><p>Conditional statements allow you to make decisions in your code based on a certain condition. They can execute different blocks of code based on whether the condition is true or false.</p><p>example:</p><pre>let age = 25;<br><br>if (age &gt; 18) {<br>  console.log(&quot;You are an adult&quot;);<br>} else {<br>  console.log(&quot;You are not an adult&quot;);<br>}</pre><h3>6: Loops</h3><ol><li>Loops allow you to repeat a block of code multiple times. There are several types of loops in JavaScript, including for loops, while loops, and do-while loops.</li></ol><p>example:</p><pre>let myArray = [1, 2, 3, 4, 5];<br><br>for (let i = 0; i &lt; myArray.length; i++) {<br>  console.log(myArray[i]);<br>}</pre><h3>7: DOM Manipulation:</h3><p>The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. In JavaScript, you can manipulate the DOM to create dynamic web pages.</p><p>example:</p><pre>let myElement = document.getElementById(&quot;myElement&quot;);<br>myElement.innerText = &quot;New text&quot;;</pre><h3>8: Events</h3><p>In JavaScript, events are actions or occurrences that happen in the browser, such as a button being clicked, a page being loaded, or a form being submitted. You can write event handlers to respond to these events and execute code in response to them.</p><p>Example:</p><pre>let myButton = document.getElementById(&quot;myButton&quot;);<br>myButton.addEventListener(&quot;click&quot;, function() {<br>  console.log(&quot;Button clicked&quot;);<br>});</pre><p>This code adds an event listener to a button element with the ID “myButton”. When the button is clicked, the function inside the event listener is executed, which outputs “Button clicked” to the console. Events are essential for building interactive user interfaces in ReactJS.</p><h3>9: ES6 Syntax:</h3><p>ES6 (ECMAScript 2015) is a major update to the JavaScript language, which introduced new features and syntax to make the language more powerful and expressive. Many of these features, such as arrow functions, template literals, and destructuring, are commonly used in ReactJs development.</p><p>example:</p><pre>const myFunction = (name) =&gt; {<br>  console.log(`Hello, ${name}!`);<br>};<br><br>myFunction(&quot;John&quot;); // outputs &quot;Hello, John!&quot; to the console</pre><h3>10: Asynchronous Programming:</h3><p>Asynchronous programming is a programming paradigm that allows multiple tasks to run simultaneously, without blocking the main thread. In JavaScript, you can use asynchronous programming techniques, such as callbacks, promises, and async/await, to write non-blocking code that can handle multiple tasks at once.</p><p>Example:</p><pre>const fetchData = async () =&gt; {<br>  const response = await fetch(&quot;https://api.example.com/data&quot;);<br>  const data = await response.json();<br>  console.log(data);<br>};<br><br>fetchData(); // fetches data from an API and logs it to the console</pre><p>Asynchronous programming is essential for building performant and responsive ReactJS applications that can handle large amounts of data and user interactions.</p><h3>11: Useful javascript methods:</h3><p>Map, filter, and reduce are three array methods that allow you to manipulate arrays in powerful and efficient ways.</p><h3>1: map() method:</h3><p>The map() method creates a new array by applying a function to each element in the original array. The function can transform the elements in any way you like, allowing you to easily modify an array without changing the original.</p><p>Example:</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const doubledNumbers = numbers.map((num) =&gt; {<br>  return num * 2;<br>});<br><br>console.log(doubledNumbers); // outputs [2, 4, 6, 8, 10]</pre><p>In this example, the map() method applies a function that doubles each number in the original array, creating a new array with the doubled values.</p><h3>2: filter() method:</h3><p>The filter() method creates a new array by filtering out elements that don’t meet a certain condition. The function passed to filter() should return a boolean value that determines whether an element should be included in the new array or not.</p><p>example:</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const evenNumbers = numbers.filter((num) =&gt; {<br>  return num % 2 === 0;<br>});<br><br>console.log(evenNumbers); // outputs [2, 4]</pre><p>In this example, the filter() method creates a new array containing only the even numbers from the original array.</p><h3>3: reduce() method:</h3><p>The reduce() method applies a function to each element in an array to reduce the array to a single value. The function should take two arguments: an accumulator (which is the value returned from the previous iteration), and the current element in the array.</p><p>example:</p><pre>const numbers = [1, 2, 3, 4, 5];<br><br>const sum = numbers.reduce((accumulator, num) =&gt; {<br>  return accumulator + num;<br>}, 0);<br><br>console.log(sum); // outputs 15</pre><p>In this example, the reduce() method applies a function that sums up all the numbers in the original array, starting with an initial value of 0.</p><p>These array methods are incredibly useful for working with arrays in JavaScript, and are frequently used in ReactJS development. By mastering these methods, you’ll be able to manipulate arrays efficiently and elegantly, making your ReactJS code more concise and readable.</p><p>By mastering these essential JavaScript concepts, you’ll be well on your way to becoming a skilled ReactJS developer and creating powerful, dynamic, and responsive user interfaces.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d6a5706ec00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Most important concepts of React JS.]]></title>
            <link>https://medium.com/@AbidKazmi/10-most-important-concepts-of-react-js-a15e93596766?source=rss-5ea716055515------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15e93596766</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[complete-react-js]]></category>
            <category><![CDATA[learn-react-js]]></category>
            <category><![CDATA[react-concept]]></category>
            <category><![CDATA[react-js-docs]]></category>
            <dc:creator><![CDATA[Kazmi]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 18:26:09 GMT</pubDate>
            <atom:updated>2023-07-12T09:17:09.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZZUt5TeFv48GoNQ76miOg.jpeg" /></figure><p>Are you looking to build dynamic and interactive web applications? Look no further than ReactJS! This popular JavaScript library is used by developers around the world to create highly performant, scalable, and maintainable applications.</p><p>In this Article we will go through the most important concepts of React js</p><h3>1: Introduction to React</h3><ul><li>What is React JS?</li><li>Why use React JS?</li></ul><h3>2: Components</h3><ul><li>What are components in React?</li><li>How to create a component?</li><li>Class Components vs Functional Components</li></ul><h3>3: JSX</h3><ul><li>What is JSX?</li><li>How to use JSX in React?</li><li>JSX vs HTML</li></ul><h3>4: Props</h3><ul><li>What are props?</li><li>How to pass props to a component?</li><li>Default Props and Prop Types</li></ul><h3>5: State</h3><ul><li>What is state in React?</li><li>How to use state in a component?</li><li>setState method and its usage</li></ul><h3>6: Lifecycle Methods</h3><ul><li>What are lifecycle methods?</li><li>Different lifecycle methods in React</li><li>How to use lifecycle methods in a component?</li></ul><h3>7: Events</h3><ul><li>What are events in React?</li><li>How to handle events in React?</li><li>Synthetic events</li></ul><h3>8: Hooks</h3><ul><li>What are hooks in React?</li><li>Different hooks in React</li><li>How to use hooks in a component?</li></ul><h3>9: Routing</h3><ul><li>What is routing in React?</li><li>How to implement routing in React?</li></ul><h3>10: Redux</h3><ul><li>What is Redux?</li><li>How to use Redux in a React application?</li></ul><h3>1: Introduction to React JS:</h3><p>React JS is a popular front-end library for building user interfaces. It was created by Facebook and is now maintained by a large community of developers. In this blog post, we’ll explore the key concepts of React JS that every beginner should know.</p><h3>2: Components</h3><p>In React, everything is a component. A component is a reusable piece of code that can be rendered to the screen. Components can be thought of as building blocks that are used to create complex user interfaces. There are two types of components in React: functional components and class components.</p><p>Functional components are JavaScript functions that return a JSX element. They are simple, stateless, and don’t have their own lifecycle methods. Class components, on the other hand, are ES6 classes that extend the React Component class. They have their own lifecycle methods and can have state.</p><p>Let’s say you want to create a reusable component for a button in your React application. You can create a functional component like this:</p><pre>import React from &#39;react&#39;;<br><br>function Button(props) {<br>  return &lt;button&gt;{props.label}&lt;/button&gt;;<br>}<br><br>export default Button;</pre><p>In this example, the Button component takes a props object as a parameter and returns a button element with a label property that is passed in as a prop.</p><h3>3: JSX</h3><p>JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It makes it easy to create components and write code that is both easy to read and easy to understand. JSX is not required in React, but it is recommended because it makes your code more readable.</p><pre>import React from &#39;react&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello World!&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this example, the App component returns a div element with an h1 element inside it.</p><h3>4: Props</h3><p>Props are short for properties and are used to pass data from one component to another. Props are read-only, which means that they cannot be modified by the child component. To pass props to a component, you simply add them as attributes to the component.</p><p>Default props are used to set default values for props, and prop types are used to specify the type of props that are expected.</p><pre>import React from &#39;react&#39;;<br>import Message from &#39;./Message&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Message message=&quot;Hello World!&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this example, the App component passes a message prop to the Message component, which displays the message on the screen.</p><h3>5: State</h3><p>State is a way to store data in a component. Unlike props, state can be modified by the component itself. When state changes, React re-renders the component and any child components. To update state, you use the setState method.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  const increment = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>In this example, the Counter component uses the useState hook to create a state variable called count and a function called setCount to update the count. The component also defines an increment function that updates the count when the button is clicked.</p><h3>6: Lifecycle Methods</h3><p>Lifecycle methods are methods that are called at different stages of a component’s life. These methods allow you to perform certain actions when a component is created, updated, or destroyed. There are several lifecycle methods in React, including componentDidMount, componentDidUpdate, and componentWillUnmount.</p><p>Lifecycle methods allow you to perform certain actions when a component is created, updated, or destroyed. Here’s an example of how to use the componentDidMount lifecycle method to fetch data from an API:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function App() {<br>  const [data, setData] = useState([]);<br><br>  useEffect(() =&gt; {<br>    fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>      .then(response =&gt; response.json())<br>      .then(json =&gt; setData(json));<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {data.map(item =&gt; (<br>        &lt;p key={item.id}&gt;{item.title}&lt;/p&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this example, the App component uses the useEffect hook to fetch data from the JSONPlaceholder API when the component mounts. The fetched data is stored in the state variable data, which is used to render a list of post titles.</p><h3>7: Events</h3><p>Events are actions that are triggered by the user, such as clicking a button or typing in a text field. In React, events are handled using synthetic events. Synthetic events are a cross-browser wrapper around the browser’s native event system.</p><pre>import React from &#39;react&#39;;<br><br>function Button() {<br>  const handleClick = () =&gt; {<br>    alert(&#39;Button clicked!&#39;);<br>  };<br><br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>}<br><br>export default Button;</pre><p>In this example, the Button component defines a handleClick function that is called when the button is</p><h3>8: Hooks</h3><p>Hooks are a new feature introduced in React 16.8. They allow you to use state and other React features in functional components. There are several hooks available in React, including useState, useEffect, and useContext.</p><p>here’s an example of how to use hooks to create a simple counter:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  const increment = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  const decrement = () =&gt; {<br>    setCount(count - 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>In this example, the useState hook is used to create a state variable called count and a function called setCount to update the count. The component also defines two functions called increment and decrement that update the count when the corresponding buttons are clicked.</p><p>The Counter component then renders the current count along with two buttons that call the increment and decrement functions respectively.</p><p>The useState hook is just one of the many hooks available in React, and they can be used to manage state, handle side effects, and more. Hooks provide a powerful and flexible way to build React applications.</p><h3>9: Routing</h3><p>Routing is the process of mapping URLs to components. In React, you can use a third-party library like React Router to implement routing in your application. With React Router, you can define routes and their corresponding components.</p><p>here’s an example of how to use routing in a React application using the React Router library:</p><pre>import React from &#39;react&#39;;<br>import { BrowserRouter as Router, Switch, Route, Link } from &#39;react-router-dom&#39;;<br><br>function Home() {<br>  return &lt;h2&gt;Home&lt;/h2&gt;;<br>}<br><br>function About() {<br>  return &lt;h2&gt;About&lt;/h2&gt;;<br>}<br><br>function Contact() {<br>  return &lt;h2&gt;Contact&lt;/h2&gt;;<br>}<br><br>function App() {<br>  return (<br>    &lt;Router&gt;<br>      &lt;div&gt;<br>        &lt;nav&gt;<br>          &lt;ul&gt;<br>            &lt;li&gt;<br>              &lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>              &lt;Link to=&quot;/about&quot;&gt;About&lt;/Link&gt;<br>            &lt;/li&gt;<br>            &lt;li&gt;<br>              &lt;Link to=&quot;/contact&quot;&gt;Contact&lt;/Link&gt;<br>            &lt;/li&gt;<br>          &lt;/ul&gt;<br>        &lt;/nav&gt;<br><br>        &lt;</pre><p>In this example, the Router component is used to define the routes for the Home, About, and Contact components.</p><p>The Link component is used to create links that navigate to each of the routes, and the Switch component is used to render the appropriate component based on the current route.</p><p>When the user clicks on a link, the URL changes and the appropriate component is rendered.</p><p>This is just a simple example of how to use routing in a React application using React Router. You can use more advanced features of React Router to handle nested routes, authentication, and more.</p><h3>10: Redux</h3><p>Redux is a state management library for JavaScript applications. It allows you to manage the state of your application in a predictable way. Redux is often used in conjunction with React to manage the state of a React application.</p><p>you can check the Redux documentation here <a href="https://redux.js.org/">https://redux.js.org</a></p><p><strong>Conclusion</strong></p><p>React JS is a powerful tool for building dynamic user interfaces. By understanding these key concepts, you’ll be well on your way to building your own React applications. Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15e93596766" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>