<?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 Tanya sharma on Medium]]></title>
        <description><![CDATA[Stories by Tanya sharma on Medium]]></description>
        <link>https://medium.com/@tanyas022000?source=rss-a172145c9369------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4GkCiMHidwHy-7guwjhVxw.jpeg</url>
            <title>Stories by Tanya sharma on Medium</title>
            <link>https://medium.com/@tanyas022000?source=rss-a172145c9369------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:59:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanyas022000/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[Secure Your React App Like a Pro: Adding OAuth 2.0 for Modern Login]]></title>
            <link>https://medium.com/@tanyas022000/secure-your-react-app-like-a-pro-adding-oauth-2-0-for-modern-login-0a674d71fae6?source=rss-a172145c9369------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a674d71fae6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[google-oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[two-factor-authentication]]></category>
            <dc:creator><![CDATA[Tanya sharma]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 07:16:44 GMT</pubDate>
            <atom:updated>2025-08-13T07:16:44.396Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever visited a website and logged in with your <strong>Google</strong> or <strong>GitHub</strong> account instead of creating a new password? That’s the magic of <strong>OAuth 2.0</strong> — the open standard powering seamless and secure sign-ins across the web.</p><p>If you’re building a React application in 2025, offering this experience is no longer a luxury — it’s expected. In this guide, we’ll cover how to integrate OAuth 2.0 into your React app the right way, using the <strong>Authorization Code with PKCE</strong> flow to keep your users (and their data) safe.</p><p>🚀 <strong>Why OAuth 2.0 Matters for React Developers</strong></p><ul><li><strong>User convenience</strong> → No more “forgot password” nightmares.</li><li><strong>Security</strong> → You never touch a user’s password; the provider handles it.</li><li><strong>Flexibility</strong> → Connect with popular identity providers (Google, Microsoft, GitHub, Okta, Auth0).</li></ul><p>Instead of storing sensitive credentials, your app just gets a <strong>secure token</strong> to access APIs on the user’s behalf.</p><h3>🔍 How the Flow Works (Without the Jargon Overload)</h3><p>The recommended approach for single-page apps (SPAs) is <strong>Authorization Code Flow with PKCE</strong>. Here’s the short version:</p><ol><li>Your app sends the user to the OAuth provider’s login page.</li><li>The user logs in and says, “Yes, this app can access my info.”</li><li>The provider sends your app a <strong>temporary code</strong>.</li><li>Your app swaps that code for an <strong>access token</strong> (and maybe a refresh token).</li><li>You use that token to make secure API calls.</li></ol><p>Think of it like checking into a hotel:</p><ul><li>The front desk (OAuth provider) verifies who you are.</li><li>They give you a keycard (token) that opens certain doors (APIs) for a set time.</li></ul><h3>🛠 Setting Up OAuth 2.0 in React</h3><p>We’ll use <strong>Auth0</strong> in our example because it’s beginner-friendly, but the same principles apply to other providers.</p><h3>1. Install the Auth0 React SDK</h3><pre>npm install @auth0/auth0-react</pre><h3>2. Wrap Your App with Auth0Provider</h3><pre>// index.js<br>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import { Auth0Provider } from &quot;@auth0/auth0-react&quot;;<br>import App from &quot;./App&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;Auth0Provider<br>    domain={process.env.REACT_APP_AUTH0_DOMAIN}<br>    clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}<br>    authorizationParams={{ redirect_uri: window.location.origin }}<br>  &gt;<br>    &lt;App /&gt;<br>  &lt;/Auth0Provider&gt;<br>);</pre><p><strong>.env</strong></p><pre>REACT_APP_AUTH0_DOMAIN=your-tenant.auth0.com<br>REACT_APP_AUTH0_CLIENT_ID=your-client-id</pre><h3>3. Add Login &amp; Logout</h3><pre>// App.js<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;<br><br>export default function App() {<br>  const { loginWithRedirect, logout, user, isAuthenticated } = useAuth0();<br><br>  return (<br>    &lt;div&gt;<br>      {!isAuthenticated ? (<br>        &lt;button onClick={() =&gt; loginWithRedirect()}&gt;Sign In&lt;/button&gt;<br>      ) : (<br>        &lt;&gt;<br>          &lt;h2&gt;Welcome, {user.name}&lt;/h2&gt;<br>          &lt;button onClick={() =&gt; logout({ returnTo: window.location.origin })}&gt;<br>            Sign Out<br>          &lt;/button&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>🔒 Protecting Private Pages</h3><pre>// PrivateRoute.js<br>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;<br>import { Navigate } from &quot;react-router-dom&quot;;<br><br>export default function PrivateRoute({ children }) {<br>  const { isAuthenticated, isLoading } = useAuth0();<br>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  return isAuthenticated ? children : &lt;Navigate to=&quot;/&quot; /&gt;;<br>}</pre><p>Usage:</p><pre>&lt;Route path=&quot;/dashboard&quot; element={&lt;PrivateRoute&gt;&lt;Dashboard /&gt;&lt;/PrivateRoute&gt;} /&gt;</pre><h3>📡 Making Secure API Calls</h3><pre>import { useAuth0 } from &quot;@auth0/auth0-react&quot;;<br><br>export default function Dashboard() {<br>  const { getAccessTokenSilently } = useAuth0();<br><br>  async function fetchData() {<br>    const token = await getAccessTokenSilently();<br>    const res = await fetch(&quot;https://api.example.com/data&quot;, {<br>      headers: { Authorization: `Bearer ${token}` }<br>    });<br>    console.log(await res.json());<br>  }<br><br>  return &lt;button onClick={fetchData}&gt;Fetch Data&lt;/button&gt;;<br>}</pre><h3>🎯 Wrapping Up</h3><p>Adding OAuth 2.0 to your React app isn’t just about security — it’s about <strong>trust</strong> and <strong>user experience</strong>. By letting users sign in with providers they already trust, you reduce friction and boost adoption.</p><p><strong>Next steps:</strong></p><ul><li>Add multiple OAuth providers (Google, GitHub, Microsoft, etc.)</li><li>Implement <strong>role-based access control</strong></li><li>Always use HTTPS in production to keep tokens secure</li></ul><p>Thank you for reading!<br> If this guide helped you get OAuth 2.0 working in your React app, I’d love to hear how you implemented it — which provider you used, whether you added a backend for refresh tokens, or any UX tweaks that improved signups. If you found this useful, please give it a clap and follow for more dev guides and practical security tips. Happy coding ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a674d71fae6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Your React.js Apps with Azure AD Authentication & MSAL]]></title>
            <link>https://medium.com/@tanyas022000/supercharge-your-react-js-apps-with-azure-ad-authentication-msal-fe3154e51688?source=rss-a172145c9369------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe3154e51688</guid>
            <category><![CDATA[msal-react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <dc:creator><![CDATA[Tanya sharma]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 11:08:40 GMT</pubDate>
            <atom:updated>2025-04-15T11:08:40.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s digital landscape, safeguarding your web applications is more important than ever. A key component of this security is effective user authentication and authorization. Azure Active Directory (Azure AD) offers a powerful solution for this, and the Microsoft Authentication Library (MSAL) simplifies the integration of Azure AD into your React.js applications. In this article, I’ll walk you through the process of integrating Azure AD authentication using the @azure/msal-browser and @azure/msal-react libraries in your React.js app. This integration will not only boost your application’s security but also enhance its usability and accessibility.</p><p>Here’s a simplified high level sequence flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0grucU8piI_qxzDGQXxWSg.png" /></figure><h3>Setup Requirements</h3><ul><li><strong>A React.js Application</strong>: If you don’t have one already, you can quickly set up a basic React.js application using Create React App: <a href="https://create-react-app.dev/">https://create-react-app.dev/</a>.</li><li><strong>Azure AD Tenant</strong>: You’ll need an Azure AD tenant to configure your application. If you don’t have one, you can easily create it through the Azure Portal.</li><li><strong>Azure AD App Registration</strong>: Register your React.js app in Azure AD by creating an Azure AD App Registration. This will provide you with the client ID and other necessary configuration details.</li></ul><h3>Integration</h3><p>Assuming that your Azure AD app is already set up and you have the necessary <strong>Client ID</strong> ,authority ,redirectUri , postLogoutRedirectUri, scopes, ready with you, follow these steps to integrate Azure AD authentication into your React.js app:</p><h3>1. Setup the MSAL Configuration File</h3><p>First, create a file, for example authConfig.ts, and place the configuration code inside it. This file holds the MSAL configuration details for your Azure AD app, including authentication parameters, cache configuration, and logging.</p><pre>import { LogLevel } from &quot;@azure/msal-browser&quot;;<br><br>export const msalConfig = {<br>  auth: {<br>    clientId: &quot;YOUR_CLIENT_ID&quot;, // Your Client ID<br>    authority: &quot;https://login.microsoftonline.com/YOUR_TENANT_ID&quot;, // Your Tenant ID<br>    redirectUri: &quot;YOUR_REDIRECT_URL&quot;, // Your Redirect URI<br>    navigateToLoginRequestUrl: true,<br>  },<br>  cache: {<br>    cacheLocation: &quot;sessionStorage&quot;, // Cache storage location (sessionStorage in this case)<br>    storeAuthStateInCookie: false, // For IE11/Edge compatibility (set to true if needed)<br>  },<br>  system: {<br>    loggerOptions: {<br>      loggerCallback: (level: any, message: any, containsPii: any) =&gt; {<br>        if (containsPii) {<br>          return; // Avoid logging PII<br>        }<br>        switch (level) {<br>          case LogLevel.Error:<br>            console.error(message);<br>            return;<br>          case LogLevel.Info:<br>            console.info(message);<br>            return;<br>          case LogLevel.Verbose:<br>            console.debug(message);<br>            return;<br>          case LogLevel.Warning:<br>            console.warn(message);<br>            return;<br>          default:<br>            return;<br>        }<br>      },<br>    },<br>  },<br>};<br><br>// Login request configuration<br>export const loginRequest = {<br>  scopes: [&quot;openid&quot;, &quot;profile&quot;, &quot;User.Read&quot;], // Scopes for the login request<br>  prompt: &quot;select_account&quot;, // Prompt to select an account during login<br>};<br><br>// Token request configuration for fetching tokens<br>export const tokenRequest = {<br>  scopes: [&quot;User.Read&quot;, &quot;Mail.Read&quot;], // Scopes for the token request<br>  forceRefresh: false, // If true, it forces a fresh token request<br>};<br><br>// Microsoft Graph API configuration<br>export const graphConfig = {<br>  graphMeEndpoint: &quot;https://graph.microsoft.com/v1.0/me&quot;, // Endpoint to get user profile information<br>};<br><br>export type LogoutType = &quot;popup&quot; | &quot;redirect&quot;; // Defines logout method type</pre><h3>2. Initialize MSAL in Your App</h3><p>Now, in your main app file (like index.tsx or App.tsx), you can import the MSAL configuration and initialize the MSAL instance using the PublicClientApplication from @azure/msal-react.</p><p>Here’s how you can set up the MSAL instance:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import { MsalProvider, PublicClientApplication } from &#39;@azure/msal-react&#39;;<br>import { msalConfig } from &#39;./authConfig&#39;; // Import the MSAL configuration<br>import App from &#39;./App&#39;;<br><br>// Initialize MSAL with the provided configuration<br>const msalInstance = new PublicClientApplication(msalConfig);<br><br>ReactDOM.render(<br>  &lt;MsalProvider instance={msalInstance}&gt;<br>    &lt;App /&gt;<br>  &lt;/MsalProvider&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><h3>3. Implement Authentication Flow</h3><p>To handle the authentication flow, such as signing in and signing out, use MSAL hooks and methods. For example:</p><pre>import React from &#39;react&#39;;<br>import { useMsal } from &#39;@azure/msal-react&#39;;<br>import { loginRequest } from &#39;./authConfig&#39;; // Import login request configuration<br><br>const SignInButton = () =&gt; {<br>  const { instance } = useMsal();<br><br>  const signIn = () =&gt; {<br>    instance.loginPopup(loginRequest) // Use loginPopup for sign-in<br>      .then(response =&gt; {<br>        console.log(&quot;User signed in&quot;, response);<br>      })<br>      .catch(error =&gt; {<br>        console.error(&quot;Error signing in&quot;, error);<br>      });<br>  };<br><br>  return &lt;button onClick={signIn}&gt;Sign In&lt;/button&gt;;<br>};<br><br>const SignOutButton = () =&gt; {<br>  const { instance } = useMsal();<br><br>  const signOut = () =&gt; {<br>    instance.logoutPopup() // Use logoutPopup for sign-out<br>      .then(() =&gt; {<br>        console.log(&quot;User signed out&quot;);<br>      })<br>      .catch(error =&gt; {<br>        console.error(&quot;Error signing out&quot;, error);<br>      });<br>  };<br><br>  return &lt;button onClick={signOut}&gt;Sign Out&lt;/button&gt;;<br>};<br><br>export { SignInButton, SignOutButton };</pre><h3>4. Protect Routes and Display Auth Status</h3><p>To conditionally render different UI based on the user’s authentication status, use the AuthenticatedTemplate and UnauthenticatedTemplate components from MSAL:</p><pre>import { AuthenticatedTemplate, UnauthenticatedTemplate } from &#39;@azure/msal-react&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;AuthenticatedTemplate&gt;<br>        &lt;h1&gt;Welcome, authenticated user!&lt;/h1&gt;<br>        &lt;SignOutButton /&gt;<br>      &lt;/AuthenticatedTemplate&gt;<br>      &lt;UnauthenticatedTemplate&gt;<br>        &lt;h1&gt;Please sign in to access the app.&lt;/h1&gt;<br>        &lt;SignInButton /&gt;<br>      &lt;/UnauthenticatedTemplate&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h3>5. Fetching Data from Microsoft Graph API</h3><p>Once the user is authenticated, you can use the access token to fetch data from the Microsoft Graph API. Here’s how to make a request to get the user’s profile:</p><pre>import { useMsal } from &#39;@azure/msal-react&#39;;<br>import { graphConfig } from &#39;./authConfig&#39;;<br><br>const Profile = () =&gt; {<br>  const { instance } = useMsal();<br><br>  const fetchProfile = async () =&gt; {<br>    const accounts = instance.getAllAccounts();<br>    if (accounts.length &gt; 0) {<br>      const accessTokenRequest = {<br>        ...loginRequest,<br>        account: accounts[0], // Use the first account<br>      };<br><br>      try {<br>        const response = await instance.acquireTokenSilent(accessTokenRequest);<br>        const accessToken = response.accessToken;<br><br>        // Fetch user data from Microsoft Graph API<br>        const res = await fetch(graphConfig.graphMeEndpoint, {<br>          headers: {<br>            Authorization: `Bearer ${accessToken}`,<br>          },<br>        });<br>        const data = await res.json();<br>        console.log(data); // Log the user profile data<br>      } catch (error) {<br>        console.error(&quot;Error fetching user profile&quot;, error);<br>      }<br>    }<br>  };<br><br>  return &lt;button onClick={fetchProfile}&gt;Get Profile&lt;/button&gt;;<br>};<br><br>export default Profile;</pre><h3>5. Fetching Data from Microsoft Graph API</h3><p>Once the user is authenticated, you can use the access token to fetch data from the Microsoft Graph API. Here’s how to make a request to get the user’s profile:</p><pre>import { useMsal } from &#39;@azure/msal-react&#39;;<br>import { graphConfig } from &#39;./authConfig&#39;;<br><br>const Profile = () =&gt; {<br>  const { instance } = useMsal();<br><br>  const fetchProfile = async () =&gt; {<br>    const accounts = instance.getAllAccounts();<br>    if (accounts.length &gt; 0) {<br>      const accessTokenRequest = {<br>        ...loginRequest,<br>        account: accounts[0], // Use the first account<br>      };<br><br>      try {<br>        const response = await instance.acquireTokenSilent(accessTokenRequest);<br>        const accessToken = response.accessToken;<br><br>        // Fetch user data from Microsoft Graph API<br>        const res = await fetch(graphConfig.graphMeEndpoint, {<br>          headers: {<br>            Authorization: `Bearer ${accessToken}`,<br>          },<br>        });<br>        const data = await res.json();<br>        console.log(data); // Log the user profile data<br>      } catch (error) {<br>        console.error(&quot;Error fetching user profile&quot;, error);<br>      }<br>    }<br>  };<br><br>  return &lt;button onClick={fetchProfile}&gt;Get Profile&lt;/button&gt;;<br>};<br><br>export default Profile;</pre><h3>Conclusion</h3><p>In this article, we’ve walked through the process of securing your React.js applications by integrating Azure Active Directory (Azure AD) authentication using the Microsoft Authentication Library (MSAL). By following the steps outlined, you can effectively ensure your application’s security, providing a seamless sign-in experience and enabling access to protected resources like the Microsoft Graph API.</p><p>Integrating Azure AD with MSAL not only enhances security but also streamlines the authentication process, making it more reliable and user-friendly. The setup we’ve covered ensures that users can sign in securely, access resources with the right permissions, and maintain their session across your application.</p><p>If you found this guide helpful, I’d really appreciate your feedback! Feel free to leave a comment, share your thoughts, or follow me for more articles on building secure, scalable applications. Your support and insights help me improve and create more valuable content for developers like you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe3154e51688" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey from a Backbencher to Google]]></title>
            <link>https://medium.com/@tanyas022000/my-journey-from-a-backbencher-to-google-41b5107d006a?source=rss-a172145c9369------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b5107d006a</guid>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[job-at-google]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[corporate]]></category>
            <dc:creator><![CDATA[Tanya sharma]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 18:57:56 GMT</pubDate>
            <atom:updated>2025-02-19T18:57:56.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*mPXWC114FsltFee-.png" /></figure><p>Hi everyone,</p><p>I want to share my journey from being an average college student — someone who sat in the back rows, didn’t have a high GPA, and wasn’t among the top scorers — to landing a job at Google.</p><p>If there’s one thing I’ve learned, it’s that <strong>consistency is the key to everything</strong> — whether it’s health, fitness, career growth, or anything else you want to achieve. No matter where you start, <strong>never lose hope, and never stop working until you reach your goal.</strong></p><h3>The Beginning: A Dream That Felt Too Big</h3><p>When I started college, I was just another student in the crowd. I wasn’t exceptionally bright, nor did I have a standout academic record. I always admired people who cracked big tech companies, but deep down, I never imagined I could be one of them. Google felt like a distant dream, something only geniuses could achieve.</p><p>But even though I didn’t have a specific company in mind, I knew I wanted a <strong>good placement</strong>. That was my goal.</p><h3>Starting Late: My DSA Journey</h3><p>Like many students, I started <strong>Data Structures &amp; Algorithms (DSA)</strong> pretty late. Initially, I didn’t even know where to begin. There were so many resources, and it was overwhelming. But then I discovered <strong>Striver’s Sheet</strong> (he’s the master!), and that changed everything.</p><p>I followed the sheet religiously, solving problems consistently. There were days when I felt stuck, days when I thought I wasn’t making progress, but I kept pushing forward.</p><p>Along the way, I also took some paid courses, but looking back, <strong>they weren’t necessary</strong>. Everything I needed was already available for free — I just had to put in the effort.</p><h3>Facing Rejection</h3><p>After months of preparation, I finally got the chance to interview at Google. I was excited and nervous at the same time. But when the results came, <strong>I got rejected</strong>.</p><p>That moment hit me hard. I had put in so much effort, yet I still wasn’t good enough. It would have been easy to give up, to think, <em>Maybe Google isn’t for me.</em></p><p>But instead, I decided to <strong>use that rejection as motivation</strong>. I analyzed my mistakes, identified my weak areas, and worked even harder. I practiced more, refined my approach, and <strong>applied again after a few months</strong>.</p><h3>The Moment of Success</h3><p>This time, things were different. My preparation was stronger, my confidence was higher, and I knew exactly what to expect.</p><p>And then, it happened — I got the offer. I was in shock. The same company that once felt like an impossible dream had now become my reality.</p><h3>Key Takeaways from My Journey</h3><p>If there’s one thing I want you to take away from my journey, it’s this:</p><ul><li><strong>Consistency beats talent</strong> — You don’t have to be a genius; you just have to show up every day and keep improving.</li><li><strong>Rejections are just redirections</strong> — Learn from them and come back stronger.</li><li><strong>Start where you are, use what you have, and do what you can</strong> — The perfect time to start doesn’t exist. Just begin.</li></ul><p>I’m still learning and growing every day, but if my journey can inspire even one person to keep pushing forward, then it’s worth sharing.</p><p>If you want to dive deeper into my experience, feel free to follow me! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b5107d006a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to Leveraging Langchain.js and Google Cloud Functions for AI-Powered Applications]]></title>
            <link>https://medium.com/@tanyas022000/a-complete-guide-to-leveraging-langchain-js-and-google-cloud-functions-for-ai-powered-applications-8d103de839cc?source=rss-a172145c9369------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d103de839cc</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[gui̇de]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <dc:creator><![CDATA[Tanya sharma]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 07:32:48 GMT</pubDate>
            <atom:updated>2024-09-06T07:32:48.884Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Langchain.js is a JavaScript/TypeScript library designed for building applications that utilize language models. It allows developers to combine various components such as models, prompts, memory, and tools, enabling the creation of more dynamic and complex AI applications. With its intuitive API and comprehensive functionality, Langchain.js simplifies the integration of natural language processing (NLP) and machine learning models into applications, without requiring in-depth knowledge of machine learning algorithms.</p><p>Meanwhile, Google Cloud Functions is a serverless computing platform provided by Google Cloud. It allows developers to deploy functions that automatically scale with demand, removing the need to manage infrastructure. This event-driven architecture enables developers to write stateless, single-purpose functions triggered by events like HTTP requests or data changes.</p><p>By integrating Langchain.js with Google Cloud Functions, developers can seamlessly build and deploy AI-powered applications that scale effortlessly, reducing operational overhead and costs typically associated with managing servers. This guide will walk you through the process of using the Langchain.js library with Google Cloud Functions, allowing you to create efficient and scalable AI applications, while leveraging the advantages of serverless computing.</p><h3>2. What is Google Cloud Functions?</h3><p><strong>Google Cloud Functions</strong> is a serverless execution environment that runs your code in response to events, without the need to manage servers. For AI applications, Cloud Functions can be used to create a lightweight and scalable API that interacts with language models or external APIs.</p><h3>3. Use Cases</h3><p>You can build the following AI-powered applications using Langchain.js and Google Cloud Functions:</p><ul><li>Text generation (e.g., summaries, translations)</li><li>Question answering</li><li>Chatbots</li><li>Code generation and analysis</li><li>Information retrieval</li></ul><h3>4. Prerequisites</h3><ol><li><strong>Google Cloud Account</strong>: To use Google Cloud Functions, you’ll need a Google Cloud account.</li><li><strong>Basic JavaScript Knowledge</strong>: This guide assumes you have a basic understanding of JavaScript, as we’ll be using it to write our Google Cloud Functions and interact with the Langchain.js library.</li><li><strong>Familiarity with Google Cloud Functions</strong>: While not mandatory, having some prior experience with Google Cloud Functions, its concepts, and how it operates will be helpful. If you’re new to it, you can learn more at <a href="https://cloud.google.com/functions">Google Cloud Functions</a>.</li></ol><p>With these prerequisites in place, let’s dive in!</p><h3>5. Supported Environments<a href="https://js.langchain.com/v0.2/docs/how_to/installation/#supported-environments">​</a></h3><p>LangChain is written in TypeScript and can be used in:</p><ul><li>Node.js (ESM and CommonJS) — 18.x, 19.x, 20.x</li><li>Cloudflare Workers</li><li>Vercel / Next.js (Browser, Serverless and Edge functions)</li><li>Supabase Edge Functions</li><li>Browser</li><li>Deno</li><li>Bun</li></ul><p>However, note that individual integrations may not be supported in all environments.</p><h3>Part 1: Setting Up Google Cloud Project and Cloud Functions</h3><h3>Setting Up Google Cloud Functions</h3><p><strong>Step 1: Create a Google Cloud Function</strong></p><p>a. Log into your Google Cloud account and head to the <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</p><p>b. From the top navigation bar, choose an existing project or create a new one by clicking the project dropdown.</p><p>c. On the left-hand sidebar, click the “Navigation Menu” (the hamburger icon) and go to “More Products” &gt; “Serverless” &gt; “Cloud Functions.”</p><p>d. Select the “Create Function” button to begin setting up a new Google Cloud Function.</p><p><strong>Step 2: Configure the Cloud Function</strong></p><p>a. <strong>Environment</strong>: Switch the environment to “2nd gen” to take advantage of the latest version of Function-as-a-Service.</p><p>b. <strong>Function Name</strong>: Assign a unique and descriptive name for your function. This will serve as its identifier in the Google Cloud Console.</p><p>c. <strong>Region</strong>: Either leave the default setting or choose the region of your preference.</p><p>d. <strong>Trigger</strong>: For this example, we will use the HTTPS trigger with no authentication. Select “Allow unauthenticated invocations.” However, remember to implement proper security and authentication measures in a production setting.</p><p>e. <strong>Runtime Variables</strong>: Click on “Runtime, build, connections and security settings,” scroll down to the “Runtime environment variables” section, and add the following:</p><ul><li><strong>Name</strong>: OPENAI_API_KEY</li><li><strong>Value</strong>: Your OpenAI API Key</li></ul><p>Now, hit the “Next” button.</p><p><strong>Step 3: Runtime and Code Settings</strong></p><p>a. <strong>Runtime</strong>: Set the runtime environment to “Node.js” and select a compatible version (this guide uses Node.js 18).</p><p>b. <strong>Default Code</strong>: You don’t need to modify the default code yet. The following sample code will be pre-filled:</p><pre>const functions = require(&#39;@google-cloud/functions-framework&#39;);<br>functions.http(&#39;helloHttp&#39;, (req, res) =&gt; {<br> res.send(`Hello ${req.query.name || req.body.name || &#39;World&#39;}!`);<br>});</pre><p><strong>Step 4: Deploy the Function</strong></p><p>Once you’ve finished configuring, click the “Deploy” button at the bottom to save and deploy your function. The process might take a few minutes.</p><p>Once the deployment completes, your function will be live, and you can copy the URL of the endpoint.</p><p><strong>Step 5: Test Your Function</strong></p><p>Congratulations! You can now test the function by sending a request to the endpoint using tools like curl, Postman, or even your browser to see the results.</p><h3>Part 2: Setting Up Langchain.js</h3><p>LangChain uses a system of packages for integrations with external services. Some packages are very focused, like @langchain/anthropic which works only with Anthropic models. Others are broader, such as @langchain/community, which includes a wider range of community-developed integrations.</p><p>These packages, along with the main LangChain package, all rely on @langchain/core. This package provides the fundamental structures that the other integration packages build upon.</p><p>To ensure all integrations and their data types work together seamlessly, they all need to use the same version of @langchain/core. This is best achieved by adding a &quot;resolutions&quot; or &quot;overrides&quot; section to your project&#39;s package.json file. The exact field name will depend on your specific package manager.</p><p>If you are using yarn:</p><pre>{<br>  &quot;name&quot;: &quot;your-project&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;&gt;=18&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@langchain/anthropic&quot;: &quot;^0.0.2&quot;,<br>    &quot;langchain&quot;: &quot;0.0.207&quot;<br>  },<br>  &quot;resolutions&quot;: {<br>    &quot;@langchain/core&quot;: &quot;0.1.5&quot;<br>  }<br>}</pre><p>Now that you’ve declared the Langchain.js library, you can use it in your Google Cloud Function. Go back to the `index.js` file and use copy code:</p><pre>import { ChatPromptTemplate } from &quot;@langchain/core/prompts&quot;;<br><br>const prompt = ChatPromptTemplate.fromMessages([<br>  [<br>    &quot;system&quot;,<br>    &quot;You are a helpful assistant that translates {input_language} to {output_language}.&quot;,<br>  ],<br>  [&quot;human&quot;, &quot;{input}&quot;],<br>]);<br><br>const chain = prompt.pipe(llm);<br>await chain.invoke({<br>  input_language: &quot;English&quot;,<br>  output_language: &quot;German&quot;,<br>  input: &quot;I love programming.&quot;,<br>});</pre><p><strong>Import Statement</strong>: This line imports the ChatPromptTemplate class from the @langchain/core/prompts module, which is used to create and manage chat-based prompt templates for language models.</p><p><strong>Prompt Creation</strong>: Here, a ChatPromptTemplate object is created using the fromMessages method. This method defines a series of messages that simulate a conversation between a &quot;system&quot; (the assistant) and a &quot;human&quot; (the user).</p><ul><li><strong>System Message</strong>: The system message instructs the assistant on its role: “You are a helpful assistant that translates {input_language} to {output_language}.” This message provides context for the translation task and uses placeholders ({input_language} and {output_language}) for dynamic content.</li><li><strong>Human Message</strong>: The human message {input} represents the text that the user wants to be translated. It is a placeholder for the input text provided during the invocation.</li><li><strong>Pipeline Setup</strong>: The pipe method connects the ChatPromptTemplate to an llm (language model). This creates a processing pipeline where the prompt template will be used to generate input for the language model.</li><li><strong>Invoke Method</strong>: The invoke method sends data through the pipeline to the language model.</li></ul><h3>Managing CORS in Google Cloud Functions</h3><p>In this section, we’ll explore how to configure your Google Cloud Function to handle cross-origin requests, addressing potential CORS (Cross-Origin Resource Sharing) issues that might arise when your function is accessed from different domains.</p><p>We will begin with the code example and then walk through the details of the adjustments made:</p><h3>Managing CORS in Google Cloud Functions</h3><p>In this section, we’ll explore how to configure your Google Cloud Function to handle cross-origin requests, addressing potential CORS (Cross-Origin Resource Sharing) issues that might arise when your function is accessed from different domains.</p><p>We will begin with the code example and then walk through the details of the adjustments made:</p><p>Here’s how you can set up your Google Cloud Function to manage CORS:</p><ol><li><strong>Update Your Function Code</strong>:</li><li>To handle CORS, you need to modify your function to include CORS headers in the HTTP response. Here’s an example of how to do this:</li></ol><pre>const functions = require(&#39;@google-cloud/functions-framework&#39;);<br><br>functions.http(&#39;myFunction&#39;, (req, res) =&gt; {<br>  // Set CORS headers<br>  res.set(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;); // Allows all origins<br>  res.set(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, OPTIONS&#39;);<br>  res.set(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);<br><br>  // Handle preflight requests (OPTIONS method)<br>  if (req.method === &#39;OPTIONS&#39;) {<br>    res.status(204).send(&#39;&#39;);<br>    return;<br>  }<br><br>  // Your main function logic<br>  res.send(&#39;Hello, world!&#39;);<br>});</pre><ol><li><strong>Explanation of Changes</strong>:</li></ol><ul><li><strong>Setting CORS Headers</strong>: The res.set() method is used to add CORS headers to the response.</li><li>Access-Control-Allow-Origin: &#39;*&#39; allows requests from any origin. For more restrictive settings, replace &#39;*&#39; with specific domains.</li><li>Access-Control-Allow-Methods: &#39;GET, POST, OPTIONS&#39; specifies which HTTP methods are allowed.</li><li>Access-Control-Allow-Headers: &#39;Content-Type, Authorization&#39; indicates which headers can be included in requests.</li><li><strong>Handling Preflight Requests</strong>: The OPTIONS method is used for preflight checks to see if the actual request is allowed. Responding with a 204 status code indicates that no content is needed for preflight requests.</li><li><strong>Function Logic</strong>: The main logic of your function processes the request and sends the appropriate response.</li></ul><p>By implementing these changes, your Google Cloud Function will be able to handle CORS requests effectively, allowing it to be accessed from various origins without running into cross-origin issues.</p><h3>Best Practices and Tips</h3><ol><li><strong>Optimize Performance</strong>:</li></ol><ul><li><strong>Keep Code Lightweight</strong>: Ensure that your serverless functions are concise and focused on specific tasks. This minimizes execution time and resource usage.</li><li><strong>Use Caching</strong>: Implement caching strategies for frequently accessed data to reduce latency and improve performance.</li></ul><p><strong>2. Error Handling</strong>:</p><ul><li><strong>Implement Robust Error Handling</strong>: Include comprehensive error handling in your functions to catch and manage unexpected issues effectively. This helps maintain application stability and reliability.</li></ul><p><strong>3. Enhance Security</strong>:</p><ul><li><strong>Authentication and Authorization</strong>: Ensure that proper authentication and authorization mechanisms are in place to safeguard your functions from unauthorized access and potential threats.</li><li><strong>Input Validation</strong>: Validate all inputs to prevent injection attacks and ensure that your functions handle data securely.</li></ul><p><strong>4. Monitor and Log</strong>:</p><ul><li><strong>Set Up Monitoring</strong>: Use tools like Google Cloud Monitoring and Google Cloud Logging to keep track of your functions’ performance and health.</li><li><strong>Review Logs Regularly</strong>: Regularly check logs to quickly identify and address any issues that arise.</li></ul><p><strong>5. Understand Function Scaling</strong>:</p><ul><li><strong>Scalability Considerations</strong>: Be aware of how your functions scale with increasing demand. Familiarize yourself with Google Cloud Functions’ scaling behavior and potential costs to manage your budget effectively.</li></ul><p><strong>6. Stay Current</strong>:</p><ul><li><strong>Update Regularly</strong>: Keep your Google Cloud Function’s runtime environment and the Langchain.js library updated to leverage the latest features, bug fixes, and security updates.</li></ul><p><strong>7. Thorough Testing</strong>:</p><ul><li><strong>Test Extensively</strong>: Conduct thorough testing of your functions both locally and in a staging environment before deploying them to production. This helps uncover and resolve issues early.</li></ul><p><strong>8. Maintain Documentation</strong>:</p><ul><li><strong>Document Functions</strong>: Create detailed documentation for your serverless functions, including configuration options, input requirements, and output formats. This will aid team members and future developers in understanding and managing the functions effectively.</li></ul><p>By adhering to these best practices, you can ensure that your serverless functions are efficient, secure, and reliable, providing a robust foundation for your applications.</p><h3>Conclusion</h3><p>In summary, this article has outlined how to effectively integrate the <strong>Langchain.js</strong> library with <strong>Google Cloud Functions</strong> to create robust and scalable natural language processing (NLP) applications. We have explored the essential tools and prerequisites needed for this integration, provided a detailed guide for setting up Google Cloud Functions, and walked through the process of installing and configuring Langchain.js.</p><p>Additionally, we addressed how to manage CORS issues to facilitate cross-origin requests, and we offered best practices for optimizing performance, ensuring security, and handling scalability challenges in your serverless functions.</p><p>By leveraging the capabilities of Langchain.js and Google Cloud Functions, you can build efficient and scalable AI-driven applications tailored to a variety of use cases across different domains. Be sure to implement robust security measures and adhere to best practices to maintain the reliability and effectiveness of your solutions.</p><p>Happy coding and exploring the possibilities with these powerful tools!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d103de839cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Render A Map Component Using ‘react-google-maps’]]></title>
            <link>https://medium.com/@tanyas022000/how-to-render-a-map-component-using-react-google-maps-cdf5e4a4fbe6?source=rss-a172145c9369------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdf5e4a4fbe6</guid>
            <dc:creator><![CDATA[Tanya sharma]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 04:57:33 GMT</pubDate>
            <atom:updated>2023-06-27T04:57:33.168Z</atom:updated>
            <content:encoded><![CDATA[<p>During the development of a React project that required Google Maps integration, I discovered a valuable library called ‘react-google-maps’ that proved instrumental in resolving these compatibility issues within my React project.</p><p>Let’s get started on something very simple like getting a map to render on the page!</p><ol><li><strong>Creating Our Boilerplate Project Folder</strong></li></ol><p>To create the boilerplate project folder for our React project, we can use <a href="https://www.npmjs.com/package/create-react-app">create-react-app</a> which generates a standard template. Follow these steps:</p><p>Step 1: Install create-react-app globally by executing the following command in your command-line interface:</p><pre>npm install -g create-react-app</pre><p>Step 2: Once create-react-app is installed, navigate to the desired location where you want to create your project folder.</p><p>Step 3: Create the project folder by running the following command:</p><pre>create-react-app project-Name</pre><p>Step 4: Once the project folder is created, navigate into it using the command:</p><pre>cd project-name</pre><p>I am using VS Code as the code editor. So, In VS code lets run :</p><pre>npm start</pre><p>If you can see this page on local host , then we are ready to get started :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*DywIRftBTnrbxte0.png" /></figure><p><strong>2. Creating The Map Component</strong></p><p>Next, navigate to the ‘src’ directory within our project folder (google-map-tutorial) and create a new folder named ‘components’. Alternatively, you can directly execute the following command from the root of our project folder:</p><pre>mkdir src/components</pre><p>Then let’s make our map component by running:</p><pre>touch src/components/Map.js</pre><p>Next, open Map.js in your text editor and let’s get cracking!</p><pre>import React, { Component } from &#39;react&#39;;<br>class Map extends Component {<br>  render(){<br>    return(<br>      &lt;div&gt;Map Template&lt;/div&gt;<br>    );<br>  }<br>};<br>export default Map;</pre><p>Now you have a basic Map component that can be used in your project.</p><p>Now, In App.js let’s render this component :</p><pre>import React, { Component } from &#39;react&#39;;<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;<br>import Map from &#39;./components/Map.js&#39;class App extends Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;App&quot;&gt;<br>        &lt;header className=&quot;App-header&quot;&gt;<br>          &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>          &lt;h1 className=&quot;App-title&quot;&gt;Welcome to React&lt;/h1&gt;<br>        &lt;/header&gt;<br>        &lt;Map/&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>};<br>export default App;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*GQUEIkNBNqbffG2c.png" /></figure><p><strong>3. Building Out The Map Component</strong></p><p>To incorporate the ‘google-maps-react’ library into our project and utilize it for building the map component, follow these steps:</p><ol><li>Make sure we are in the root directory of your project.</li><li>If we used create-react-app to set up our project, yarn should already be installed. In the command-line interface, execute the following command to install the ‘google-maps-react’ library:</li></ol><pre>yarn add google-maps-react</pre><p>Now adding maps to our Map.js file :</p><pre>import React, { Component } from &#39;react&#39;;<br>import { withGoogleMap, GoogleMap } from &#39;react-google-maps&#39;;<br>class Map extends Component {<br>   render() <br>{   <br>const GoogleMapExample = withGoogleMap(props =&gt; (<br>      &lt;GoogleMap<br>        defaultCenter = { { lat: a, lng: b} }<br>        defaultZoom = { x }<br>      &gt;<br>      &lt;/GoogleMap&gt;<br>   ));   return(<br>      &lt;div&gt;<br>        &lt;GoogleMapExample<br>          containerElement={ &lt;div style={{ height: `500px`, width: &#39;500px&#39; }}/&gt; }<br>          mapElement={ <br>&lt;div style={{ height: `100%` }} /&gt; <br>}<br>        /&gt;<br>      &lt;/div&gt;<br>   );   }<br>};<br>export default Map;</pre><p>Let me explain what’s going on here:</p><p>First, we import ‘withGoogleMap’, which is a Higher Order Component, and ‘GoogleMap’ from the ‘react-google-maps’ library.<br>Then, we create a constant that utilises both of the imported components. To make the ‘GoogleMap’ component work, we need to provide two props: ‘defaultCenter’ and ‘defaultZoom’. ‘defaultCenter’ expects an object with latitude and longitude values, while ‘defaultZoom’ requires a numeric value indicating the initial zoom level.<br>Next, we return the created constant within a div that accepts ‘containerElement’ and ‘mapElement’ props. The ‘containerElement’ holds our map element, and its size can be customized as needed. In this example, I have chosen a size of 500px by 500px. For the ‘mapElement’, I have set it to occupy 100% of the container, filling it entirely.</p><p>If you did all that correctly and saved, you should now get this in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*L8_cd7IOsKTGhr5s.png" /></figure><p>Now we have to connect everything with Google API.</p><p><strong>3. Visualizing The Map Component</strong></p><p>The initial step is to acquire an API key from Google. Remember to keep your API key confidential and refrain from sharing it publicly. Once you have obtained the API key, proceed to the index.html file located in the project’s public folder.</p><p>In this tutorial, we will add a script tag directly to the index file. However, you can explore the ‘withScriptJS’ Higher Order Component (HOC) in the react-google-maps library for a more refined approach.</p><p>To implement the script tag, locate the header section of your index.html file and insert the following script (preferably after the link tags) along with your private Google API key:</p><pre>&lt;script src=&quot;https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_GOES_HERE&quot;&gt;&lt;/script&gt;</pre><p>Now, if you did everything correctly, you should end up with a map in your browser.</p><p>There are some great features in the react-google-maps library like markers, infomarkers, and directions rendering. Follow the documentation and good luck tinkering!</p><p>In conclusion, I hope I was able to assist you in getting started with displaying a map on a page. Having a widely used service like Google Maps integrated into your React project can greatly enhance the user experience. If you have any further questions or need additional assistance, feel free to ask. Happy mapping!</p><p><strong>Feel free to review and help me in enhancing the documentation.</strong></p><p>Thank you for the reading this blog :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdf5e4a4fbe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux Vs Context-API]]></title>
            <link>https://medium.com/@tanyas022000/redux-vs-context-api-45e5bae61df2?source=rss-a172145c9369------2</link>
            <guid isPermaLink="false">https://medium.com/p/45e5bae61df2</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Tanya sharma]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 11:13:41 GMT</pubDate>
            <atom:updated>2023-06-05T19:21:19.367Z</atom:updated>
            <content:encoded><![CDATA[<p>As React has risen in popularity as one of the leading JavaScript libraries for front-end development, developers now have multiple options for managing complex application states. Among these options, React Context API and Redux are widely utilised for state management in React applications. While both aim to solve the same problem, they offer distinct approaches and advantages. Consequently, selecting between React Context API and Redux can present a challenging decision for developers, particularly those who are new to React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M17L17cu38wERdzhlBAlw.png" /></figure><h3>What is context API?</h3><blockquote>React Context API is a part of the React library that allows you to pass data down the component tree without explicitly passing the props through every level. It provides a way to share data between components, even if they are not directly related or nested in each other.</blockquote><p>To get started with Context API, there is no additional package or library required, it is a built-in feature in React. You can just simply follow these simple steps to set it up.</p><ol><li>Create a <strong>Context</strong> in a separate file</li></ol><pre>import { createContext } from &#39;react&#39;;<br><br>export const MyContext = createContext(&quot;&quot;);</pre><p>2. Create a <strong>Provider</strong> for the <strong>Context</strong> that you have created in step 1.</p><pre>// Create a parent component that wraps child components with a Provider<br><br>import { useState, React } from &quot;react&quot;;<br>import { MyContext } from &quot;./MyContext&quot;;<br>import MyComponent from &quot;./MyComponent&quot;;<br><br>function App() {<br>  const [text, setText] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;MyContext.Provider value={{ text, setText }}&gt;<br>        &lt;MyComponent /&gt;<br>      &lt;/MyContext.Provider&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>3. Use the <strong>Context</strong> in your React component</p><pre>import { useContext } from &#39;react&#39;;<br>import { MyContext } from &#39;./MyContext&#39;;<br><br>function MyComponent() {<br>  const { text, setText } = useContext(MyContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{text}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setText(&#39;Hello, world!&#39;)}&gt;<br>        Click me<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MyComponent;</pre><p>Advantages of Context Api :</p><ol><li><strong>It simplifies the data-sharing process</strong></li><li><strong>It offers a convenient alternative to prop drilling</strong></li><li><strong>It allows for efficient updates</strong></li></ol><h3>Redux</h3><blockquote>Redux is a popular JavaScript library commonly used with React for managing state in applications. It follows a predictable state container pattern and provides a centralised store to hold the application state.</blockquote><ol><li>Install Redux Library</li></ol><pre>npm install @reduxjs/toolkit react-redux</pre><p>2. Create a Slice</p><pre>import { createSlice, PayloadAction } from &#39;@reduxjs/toolkit&#39;;<br><br>interface State {<br>  count: number;<br>}<br><br>const initialState: State = {<br>  count: 0<br>};<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState,<br>  reducers: {<br>    increment: (state) =&gt; {<br>      state.count += 1;<br>    },<br>    decrement: (state) =&gt; {<br>      state.count -= 1;<br>    }<br>  }<br>});<br><br>export const { increment, decrement } = counterSlice.actions;<br><br>export default counterSlice.reducer;</pre><p>3. Create a redux <strong>Store</strong> with the <strong>Slice</strong> that you have created above.</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import counterReducer from &#39;./counterSlice&#39;;<br><br>const store = configureStore({<br>  reducer: {<br>    counter: counterReducer<br>  }<br>});<br><br>export default store;<br></pre><p>4. Create the Store that you have created above to your React components</p><pre>import React, { useCallback } from &#39;react&#39;;<br>import { useDispatch, useSelector } from &#39;react-redux&#39;;<br>import { increment, decrement } from &#39;./counterSlice&#39;;<br>import store from &#39;./store&#39;;<br><br>const Counter = () =&gt; {<br>  const count = useSelector((state: any) =&gt; state.counter.count);<br>  const dispatch = useDispatch();<br><br>  const handleIncrement = useCallback(() =&gt; {<br>    dispatch(increment());<br>  }, [dispatch]);<br><br>  const handleDecrement = useCallback(() =&gt; {<br>    dispatch(decrement());<br>  }, [dispatch]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={handleIncrement}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={handleDecrement}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>5. Lastly, wrap your component with a <strong>Provider</strong> from Redux library and point the store argument to the store that you have created above.</p><pre>import React from &#39;react&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import store from &#39;./store&#39;;<br>import Counter from &#39;./Counter&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;Counter /&gt;<br>    &lt;/Provider&gt;<br>  );<br>}<br><br>export default App;</pre><p>Here are some advantages of using Redux:</p><ol><li><strong>Centralized state management</strong>: Redux provides a centralised location for storing the state of an application, which makes it easier to manage and debug.</li><li><strong>Predictable state updates</strong>: Since the state of an application can only be updated through actions and reducers, the state changes become predictable and easy to reason about.</li><li><strong>Time-travel debugging</strong>: Redux allows you to trace the state of an application at any point in time, which makes debugging easier.</li></ol><h3>Differences between React Context API and Redux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*nvjlFnZc9Wx7-AOsaGZiHg.png" /></figure><h3>When to use React Context API vs Redux?</h3><p>The decision to use React Context API or Redux depends on the specific needs and complexity of your application.</p><p>Use <strong>React Context API</strong>:<br>1. Small to medium-sized applications</p><p>2. Fewer levels of data sharing</p><p>3. Component-specific state:</p><p>Use <strong>Redux:</strong><br>1. Large and complex applications</p><p>2. Deeply nested components</p><p>3. Asynchronous data flow</p><p>Ultimately, it’s important to assess the specific needs, complexity, and scale of your application to determine whether React Context API or Redux is the most suitable choice for state management. In some cases, a combination of both tools may be appropriate, with React Context API used for local state management and Redux utilized for global state management.</p><h3>Conclusion</h3><p>In summary, React Context API is a simpler solution suitable for smaller applications with simple state management needs, while Redux is a more powerful solution suitable for larger and more complex applications with advanced state management needs.</p><p><em>Ultimately, the choice between React Context API and Redux depends on the unique needs and constraints of your application.</em></p><p><strong>Feel free to review and help me in enhancing the documentation.</strong></p><p>Thank you for the reading this blog :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45e5bae61df2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>