<?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"><channel><title><![CDATA[Rahman's blog]]></title><description><![CDATA[Rahman's blog]]></description><link>https://tayo.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 08 Oct 2026 16:11:59 GMT</lastBuildDate><atom:link href="https://tayo.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[JSX vs TSX : The battle for React supremacy]]></title><description><![CDATA[In the kingdom of React development, there is a fierce rivalry on the syntax battleground. TSX and JSX, the two contenders fighting for supremacy. This fight has sparked debates, divided developers, and caused a never-ending quest for the perfect syn...]]></description><link>https://tayo.hashnode.dev/jsx-vs-tsx-the-battle-for-react-supremacy</link><guid isPermaLink="true">https://tayo.hashnode.dev/jsx-vs-tsx-the-battle-for-react-supremacy</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Abdulrahman Rufai]]></dc:creator><pubDate>Wed, 14 Feb 2024 22:14:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707947309820/87b22883-bb33-4c9f-ad35-997b392a3dbf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the kingdom of React development, there is a fierce rivalry on the syntax battleground. TSX and JSX, the two contenders fighting for supremacy. This fight has sparked debates, divided developers, and caused a never-ending quest for the perfect syntax. As the front-end development world thrives on innovation, TypeScript, with its type-checking powers, has become the talk of the town, it is hyped everywhere on social media adding an extra layer of excitement to the battle.</p>
<p>In this article, we will explore the clash between TSX and JSX, look at their strengths and weaknesses, and learn about the hype surrounding TypeScript in the React kingdom. Buckle up, fellow developers, as we embark on a quest to decide which one reigns supreme in the kingdom of React. The hype is real, the stakes are high – let the battle begin!</p>
<p>Here are the contents:</p>
<ol>
<li><p><strong>Introduction</strong></p>
<ul>
<li><p>Brief overview of React syntax</p>
</li>
<li><p>Importance of choosing between TSX and JSX</p>
</li>
</ul>
</li>
<li><p><strong>Understanding JSX</strong></p>
<ul>
<li><p>Explanation of JSX syntax in React</p>
</li>
<li><p>Benefits and drawbacks</p>
</li>
</ul>
</li>
<li><p><strong>Introducing TSX</strong></p>
<ul>
<li><p>Overview of TypeScript in React</p>
</li>
<li><p>Advantages and challenges of TSX</p>
</li>
</ul>
</li>
<li><p><strong>The Battle begins: TSX vs JSX</strong></p>
<ul>
<li><p>Head-to-head comparison</p>
</li>
<li><p>Use cases for each syntax</p>
</li>
</ul>
</li>
<li><p><strong>Conclusion</strong></p>
<ul>
<li><p>Summary of key considerations</p>
</li>
<li><p>Encouragement for developers navigating the TSX vs JSX dilemma</p>
</li>
</ul>
</li>
</ol>
<p>Now lets get into the details.</p>
<h1 id="heading-1-introduction"><strong>1. Introduction:</strong></h1>
<ul>
<li><em>Brief Overview of React Syntax</em></li>
</ul>
<p>React is a JavaScript library used for building user interfaces. It introduces a dynamic and declarative syntax that makes the creation of interactive components very easy. React's syntax mainly revolves around the concept of components. This part is a start to the basic ideas of how React works. It will get you ready to look more into picking between TSX and JSX.</p>
<ul>
<li><em>Importance of Choosing Between TSX and JSX</em></li>
</ul>
<p>As developers embark on React projects, one of the hard decisions they face is choosing between TSX (TypeScript XML) and JSX (JavaScript XML). Choosing between TSX and JSX is very important because it affects how we work, how easy it is to manage our code, and the overall success of our app. This part talks about how crucial this choice is, getting us ready to make smart decisions. In the next section we will look at the background of the 2 rivals.</p>
<h1 id="heading-2-understanding-jsx"><strong>2. Understanding JSX:</strong></h1>
<ul>
<li><em>Explanation of JSX Syntax in React</em></li>
</ul>
<p>JSX, short for JavaScript XML, is like a special way to write javascript code in React. It helps describe how our user interface looks. With JSX, we can write UI elements in a way that looks a lot like HTML or XML right inside our JavaScript code. This makes our React code easier to read and understand.</p>
<p><strong>JSX Syntax Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> element = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, JSX!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
</code></pre>
<p>In this example, the JSX syntax is used to create a React element representing an <code>&lt;h1&gt;</code> heading with the text "Hello, JSX!". This syntax makes the process of defining UI components and their structure very easy.</p>
<p>JSX has a lot of benefits but it also comes with its own drawbacks too. The benefits are JSX makes React code much easier to read because it looks a lot like HTML. This makes it friendlier and more familiar for developers. Also, JSX easily works with JavaScript expressions, allowing us to smoothly oerform javascript functions in our code</p>
<p><strong>Drawbacks of JSX:</strong> While JSX has a lot of benefits, it comes with a learning curve, particularly for developers new to it. Although, if you're solid with vanilla Javascript, you should be able to handle the curves. Also, some tools might need a bit of setup to fully understand JSX. This could make it tough at the beginning. For developers who really like to keep HTML and JavaScript separate, JSX's mix of HTML and Javascript might be a bit challenging.</p>
<h1 id="heading-3-introducing-tsx"><strong>3. Introducing TSX:</strong></h1>
<ul>
<li><em>Overview of TypeScript in React</em></li>
</ul>
<p>TSX, or TypeScript XML, is the fusion of TypeScript—a statically typed superset of JavaScript—with JSX syntax in React. This brings static typing to React components, making the code more predictable and reliable as we develop.</p>
<ul>
<li><em>Advantages and Challenges of TSX</em></li>
</ul>
<h3 id="heading-advantages-of-tsx"><strong>Advantages of TSX:</strong></h3>
<p><strong>Type Safety</strong>: TSX offer type safety, that is it empowers developers to define the types and enforce types for variables, components, and props. This helps in detecting error early and makes code more reliable.</p>
<p><strong>Enhanced Tooling:</strong> TypeScript brings tooling support, which include autocompletion, improved code navigation, and enhanced documentation. This makes a developer's coding experience to be very friendly and also efficient.</p>
<p><strong>Collaboration:</strong> With type annotations (that is the declared types) acting like notes, TSX makes it easier to communicate and understand the types of data expected in components. This helps a lot when you're working in teams and makes development better.</p>
<h3 id="heading-challenges-of-tsx"><strong>Challenges of TSX:</strong></h3>
<p><strong>Learning Curve:</strong> The use of TSX may present a learning curve for developers unfamiliar with TypeScript. However, the benefits gained over time eventually makes the learning curve to be worth it.</p>
<p><strong>Development Setup:</strong> Configuring a project to support TypeScript and TSX may require additional setup compared to traditional JavaScript/JSX projects.<br />Setting things up at the beginning is needed, but it's just a small bit of extra work.</p>
<p><strong>Stricter Rules:</strong> TypeScript enforces stricter rules compared to JavaScript.<br />Adding these rules might make things a bit strict, but these rules help keep the code consistent and reliable over the long run.</p>
<pre><code class="lang-javascript">interface GreetingProps {
  <span class="hljs-attr">message</span>: string;
}

<span class="hljs-keyword">const</span> Greeting: React.FC&lt;GreetingProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ message }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{message}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
};
</code></pre>
<p>In this TSX example, an interface <code>GreetingProps</code> defines the expected prop type, ensuring that the <code>message</code> prop must be a string. This shows us how TSX allows developers to declare and enforce types, contributing to a more efficient development process.</p>
<h1 id="heading-4-the-battle-begins-tsx-vs-jsx"><strong>4. The Battle Begins: TSX vs JSX:</strong></h1>
<ul>
<li><em>Head-to-Head Comparison</em></li>
</ul>
<p>In the clash between TSX and JSX, looking closely at both syntaxes shows how different they are. This will help you decide which one to use. Let's look at them</p>
<p><strong>File Extensions:</strong></p>
<ul>
<li><p>JSX files uses <code>.jsx</code> or <code>.js</code> extensions.</p>
</li>
<li><p>TSX files use the <code>.tsx</code> extension, indicating TypeScript integration.</p>
</li>
</ul>
<p><strong>Type Annotations:</strong></p>
<ul>
<li><p>JSX needs PropTypes or notes for type info.</p>
</li>
<li><p>TSX brings static typing, letting developers clearly define and enforce types.</p>
</li>
</ul>
<p><strong>Learning Curve:</strong></p>
<ul>
<li><p>JSX is generally easier to learn for developers familiar with HTML.</p>
</li>
<li><p>TSX, with its static typing, may have a steeper learning curve, especially for those new to TypeScript.</p>
</li>
</ul>
<p><strong>Tooling Support:</strong></p>
<ul>
<li><p>JSX has good tools, but you might need extra setup for TypeScript.</p>
</li>
<li><p>TSX, being all about TypeScript, already comes with advanced tools without needing extra setup</p>
</li>
</ul>
<p><strong>Project Complexity:</strong></p>
<ul>
<li><p><em>JSX is w</em>ell-suited for smaller projects and quick prototyping because it is simple.</p>
</li>
<li><p><em>TSX is</em> preferable for larger, more complex projects because static typing helps handle complex parts of the code.</p>
</li>
</ul>
<p><strong>Development Workflows:</strong></p>
<ul>
<li><p><em>JSX s</em>upports efficient development workflows, particularly in smaller projects.</p>
</li>
<li><p><em>TSX</em> introduces additional benefits such as early error detection, contributing to smoother development workflows in larger projects.</p>
</li>
</ul>
<p><strong>Collaboration within Teams:</strong></p>
<ul>
<li><p><em>JSX</em> simplifies collaboration when team members are more comfortable with a familiar syntax.</p>
</li>
<li><p><em>TSX</em> enhances collaboration through explicit type annotations and advanced tooling support, promoting better code understanding.</p>
</li>
</ul>
<p><strong>Project Maintenance:</strong></p>
<ul>
<li><p>JSX is well-suited for projects where simplicity is needed over strict typing.</p>
</li>
<li><p>TSX povides a robust foundation for long-term maintenance, minimizing the risk of runtime errors.</p>
<p>  After seeing this epic head to head battle, lets see the use cases of each syntax</p>
</li>
<li><p><em>Use Cases for Each Syntax</em></p>
</li>
</ul>
<p><strong>JSX Use Cases:</strong></p>
<ol>
<li><p><strong>Quick Prototyping:</strong> JSX is short and sweet, perfect for quickly trying out ideas and making simple components.</p>
</li>
<li><p><strong>Learning Projects:</strong> In educational or simpler projects, JSX might be preferred for its accessibility.</p>
</li>
</ol>
<p><strong>TSX Use Cases:</strong></p>
<ol>
<li><p><strong>Large Projects:</strong> In larger and more complex projects, TSX's static typing gives us the advantage of catching errors early and maintaining code integrity.</p>
</li>
<li><p><strong>Collaborative Environments:</strong> TSX's explicit type annotations serve as documentation and helps in enhancing collaboration within development teams.</p>
</li>
<li><p><strong>Enhanced Tooling:</strong> Projects that benefit from enhanced tooling support, including autocompletion and navigation, are well-suited for TSX.</p>
</li>
</ol>
<p>In the battle between TSX and JSX, choosing between TSX and JSX relies on what your project needs, what your team is good at, and figuring out the best balance between simplicity and advancement. JSX is common and easy, while TSX is great for strong type checking, better tools, and big projects. The use cases help developers pick what suits their project best.</p>
<h1 id="heading-5-conclusion"><strong>5. Conclusion:</strong></h1>
<ul>
<li><em>Summary of Key Considerations</em></li>
</ul>
<p>In the quest to choose between TSX and JSX for React development, we've talked about things to think about when making a choice. Each option has good parts, not-so-good parts, and things to consider for real projects. Deciding depends on what a project needs.</p>
<p><strong>For JSX:</strong></p>
<ul>
<li><p>JSX offers simplicity and quick prototyping.</p>
</li>
<li><p>It is well-suited for smaller projects and developers transitioning from HTML.</p>
</li>
<li><p>It's easy to use, and lots of people support it, making development smoother.</p>
</li>
</ul>
<p><strong>For TSX:</strong></p>
<ul>
<li><p>TSX introduces static typing, enhancing code reliability and early error detection.</p>
</li>
<li><p>It excels in larger projects, fostering collaboration through explicit type annotations and good tooling support.</p>
</li>
<li><p>The learning curve and initial setup are later seen to be worth it in the long-run.</p>
<p>  <em>Encouragement for Developers Navigating the TSX vs JSX Dilemma</em></p>
</li>
</ul>
<p>To developers trying to decide between TSX and JSX in React, remember that React gives you flexibility. The choice isn't one-size-fits-all but depends on your project and team preferences.</p>
<p>Think about your project's size, complexity, and your team's skills when making this decision. Don't be afraid of the learning curve; new tools mean new chances to learn and grow. Whether you choose the familiar JSX or the powerful TSX, you can always lmprove on it.</p>
<p>Choosing a syntax is a journey. Learn from others and be consistent. React is always changing, and the TSX vs JSX decision is just one part of your journey.</p>
<p>As you start your React projects, pick a syntax based on what your project needs and team preferences. Thank you for reading. You can check out more of my articles at <a target="_blank" href="https://tayo.hashnode.dev/">tayo.hashnode.dev</a></p>
]]></content:encoded></item><item><title><![CDATA[Mastering React's Context API]]></title><description><![CDATA[Have you ever wondered how to manage your states across different parts of the application or pass down props from parent components to different children components? Well, this can be done easily with props drilling but can be a crucial challenge wh...]]></description><link>https://tayo.hashnode.dev/mastering-reacts-context-api</link><guid isPermaLink="true">https://tayo.hashnode.dev/mastering-reacts-context-api</guid><category><![CDATA[React]]></category><category><![CDATA[react hooks]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Abdulrahman Rufai]]></dc:creator><pubDate>Tue, 14 Nov 2023 21:01:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1699649934932/5338b814-975d-426e-b1d5-992fa00ec2db.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever wondered how to manage your states across different parts of the application or pass down props from parent components to different children components? Well, this can be done easily with props drilling but can be a crucial challenge when you application becomes more complex. Now imagine a central state where you can store all your data, modify it the way you want and just call them anytime in any part of your React application, that sounds exciting right? That is what Context API is all about.</p>
<p>The Context Application Program Interface popularly known as Context API provides a elegant solution to challenges involving passing down data, offering a way to pass data through the component tree without the need for explicit prop drilling.</p>
<p>In this comprehensive guide, we'll delve into the intricacies of React's Context API—a powerful tool that simplifies the sharing of state across component. Whether you're a seasoned React developer or just starting your journey, this guide will walk you through the fundamentals of the Context API, its implementation, and best practices.</p>
<p>By the end of this article, you'll be equipped with the knowledge and skills to leverage the Context API effectively. Let's embark on this journey to master the art of state management with React's Context API.</p>
<p>Let's get into the full details now.</p>
<h3 id="heading-1-introduction"><strong>1. Introduction</strong></h3>
<p>• Overview of state management in React:</p>
<p>React, renowned for its declarative and component-based architecture, thrives on the concept of state. State encapsulates the dynamic information within a component, influencing its rendering and behavior. In the early stages of application development, managing state might seem straightforward. However, as the applications scale and components proliferate, the challenges of passing state between components become apparent.</p>
<p>The challenge intensifies in larger applications, where the traditional approach of prop drilling (passing state through component props) becomes a cumbersome task. Prop drilling, like navigating through a dense forest, involves passing state down multiple layers of components, resulting in code that is less readable and more prone to errors. This complexity hinders the scalability and maintainability of the application.</p>
<p>• Introduction to the Context API:</p>
<p>Enter the savior - React's Context API. The Context API provides a centralized and elegant solution to the challenges posed by prop drilling. It introduces the concept of Context, offering a way to share values like themes, authentication status, or any other application state seamlessly across the entire component tree.</p>
<h3 id="heading-2-understanding-context"><strong>2. Understanding Context</strong></h3>
<ul>
<li>What is Context and Its Role in React:</li>
</ul>
<p>Context is essentially a container for state and props that can be accessed by any component within its scope. It eliminates the need for prop drilling. Context acts as a channel through which data can flow down the component tree without the hassle of explicitly passing props through each intermediate component.</p>
<p>The primary components of context include:</p>
<p><strong>Provider</strong>: The provider component encapsulates the section of the component tree where the context is made available. It defines the data or state to be shared.</p>
<p><strong>Consumer</strong>: The consumer component is used within other components to access the data stored in the context. It subscribes to changes in the context and re-renders whenever the context data is updated.</p>
<ul>
<li>When to Use Context:</li>
</ul>
<p><strong>Prop drilling complexity:</strong></p>
<p>Scenario: Prop drilling gets cumbersome as your React app grows.</p>
<p>Why Context: Elegant solution, sharing data without explicit prop passing through every level.</p>
<p><strong>Global state management:</strong></p>
<p>Scenario: Data like authentication status or theme settings needed globally.</p>
<p>Why Context: Acts as a global state manager, accessible and updatable by components at any depth.</p>
<p><strong>Themable Components:</strong></p>
<p>Scenario: Building a themable app requiring consistent themes.</p>
<p>Why Context: Defines the theme at a higher level, shared across components, ensuring UI consistency without manual prop passing.</p>
<p><strong>Multi-step form navigation:</strong></p>
<p>Scenario: Data needs to move between steps of a form seamlessly.</p>
<p>Why Context: Simplifies data sharing in multi-step forms, enhancing the modularity of each form section</p>
<h3 id="heading-3-creating-a-context"><strong>3. Creating a Context</strong></h3>
<ul>
<li>How to create a Context in React</li>
</ul>
<p>In React, creating a context involves utilizing the <code>createContext</code> function, a method within the Context API that establishes a centralized state container.</p>
<p>To initiate the creation of a context, you start by importing the <code>createContext</code> function from the React library:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<p>The <code>createContext</code> function, when invoked, returns an object with two components: Provider and Consumer which we will look into details in the next section.</p>
<p>The <code>createContext</code> function can be invoked with or without an initial value, depending on your use case. If no initial value is provided, the context will be initialized with undefined.</p>
<p>Without an initial value:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MyContext = createContext();
</code></pre>
<p>With an initial value:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MyContext = createContext(<span class="hljs-string">'default value'</span>);
</code></pre>
<p>This context object, in our examples represented by <code>MyContext</code>, becomes the hub through which data can flow across the component tree.</p>
<p>• Exploring the <code>CreateContext</code> function</p>
<p>Let's take a practical example of creating a context with the <code>createContext</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import necessary modules</span>

<span class="hljs-keyword">import</span> React, { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-comment">// Create a context with an initial value</span>

<span class="hljs-keyword">const</span> ThemeContext = createContext(<span class="hljs-string">'light'</span>);

<span class="hljs-comment">// Export the context for usage in other components</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ThemeContext;
</code></pre>
<p>In this example, we've created a <code>ThemeContext</code> with an initial value of 'light'. This context can now be imported and used throughout your application.</p>
<p>While the initial value is specified during context creation, it's important to note that the context values can dynamically change during the runtime of your application. This is often achieved through the use of a Provider component, which we will delve into in the next section.</p>
<h3 id="heading-4-provider-and-consumer-components"><strong>4. Provider and Consumer components</strong></h3>
<p>Within the framework of React's Context API, the Provider and Consumer components stand as essential actors, each playing a unique role in the sharing and access of data. This section will introduce these components demonstrating how they collectively facilitate the efficient exchange of information within your application.</p>
<p>• Introduction to Provider and Consumer Components:</p>
<p><strong>Provider component:</strong> The Provider component, as its name suggests, is a key player in supplying data to your application. It wraps a portion of your component tree, defining the scope within which the context is accessible. Essentially, it serves as the source of truth, holding the data you want to share with other components. Let's take a look at an example of implementing a Provider below</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ThemeProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {

<span class="hljs-keyword">const</span> theme = <span class="hljs-string">'dark'</span>;

<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{theme}</span>&gt;</span>
    {children}
<span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Provider</span>&gt;</span></span>
);
};
</code></pre>
<p>In this example, the Provider <code>ThemeProvider</code>, establishes the <code>theme</code> and provides access through the <code>ThemeContext</code>.</p>
<p><strong>Consumer component:</strong> The Consumer component, on the other hand is tasked with consuming the data made available by the Provider. It is used within other components to access and utilize the data stored in the context. Consumers "subscribe" to the context, ensuring that they receive updates when the context's data changes. In simple terms let's say consuming is calling and using the Context anywhere and anytime we want. This is where we use the <code>useContext</code> hook to get dynamic access to the context data Let's take a look at an example of how to consume. For this example, let's assume you have a MyContext component established in your application which holds the Context.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { ThemeContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./ThemeContext'</span>; <span class="hljs-comment">// Import your context</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> contextValue = useContext(ThemeContext);

  <span class="hljs-comment">// Now, 'contextValue' holds the value from MyContext</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>{contextValue}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
};
</code></pre>
<p>As you can see in the example above, we've imported the <code>useContext</code> from React, we also identified the context we want to access and imported it into our component.</p>
<p>Then we Invoked the <code>useContext</code> and pass the context as an argument to it. This call returns the current context value and we can utilize the context value in our component as needed.</p>
<ul>
<li><strong>How these components work together to share data:</strong></li>
</ul>
<p>In Summary this is how the Provider and Consumer component work together and share data</p>
<p><strong>I) Set up the Provider:</strong></p>
<p>-Create a Provider to define the data to be shared.</p>
<p>-Specify the data using the <code>value</code> prop.</p>
<p><strong>II) Wrapping components:</strong></p>
<p>-Wrap components needing shared data within the Provider's scope.</p>
<p><strong>III) Access data with consumers:</strong></p>
<p>-Consumers access data through the Consumer component or <code>useContext</code>.</p>
<p>-Updates to the context data trigger re-renders for Consumers.</p>
<p>The dynamic duo of Provider and Consumer components works together seamlessly to share and access data within your React application.</p>
<h3 id="heading-5-updating-context-values"><strong>5. Updating Context Values</strong></h3>
<p>Updating context values is a crucial element of managing state and ensuring that your components can respond to changes in data. In this section, we will explore various methods for updating context values and understand when and how to use the <code>useContext</code> hook effectively.</p>
<ul>
<li>Exploring Ways to Update Context Values:</li>
</ul>
<p>In React, there are several methods to update context values. These methods are primarily used within the Provider component associated with the context. Here are some of the common ways to update context values:</p>
<p><strong>I)</strong> <strong>Using State Management:</strong> You can employ state management techniques, such as the <code>useState</code> hook, within your Provider component to maintain and update context values. When the state changes, the new value is automatically propagated to all consuming components.</p>
<p><strong>II) Function Prop in Provider:</strong> Another common approach is to provide a function as a prop within the Provider component. This function is responsible for updating the context value. Components that consume the context can call this function to make updates.</p>
<p><strong>III) Using Reducers:</strong> For more complex state management scenarios, you can utilize the <code>useReducer</code> hook within the Provider component. This allows you to dispatch actions to update the context values, following a predefined logic.</p>
<p><strong>IV) Side Effects:</strong> When dealing with asynchronous operations, you can employ <code>useEffect</code> within the Provider to trigger updates once data is fetched or modified.</p>
<h3 id="heading-6-real-world-use-cases"><strong>6. Real-World Use Cases</strong></h3>
<p>In the real world of React application development, the Context API shines in various practical scenarios. Let's delve into an illustrative example of how the Context API works. We'll do a step by step process of a themable application where users can switch from light mode to dark mode easily.</p>
<p>We will create different components and I will explain each component along with the code snippet below it. Lets start</p>
<p><strong>I)</strong> <code>App.js</code><strong>:</strong> This is the main entry point of the application. This component wraps the entire application with the <code>ThemeProvider</code>, which provides theme-related functionality to its child components.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { ThemeProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'./ThemeContext'</span>; <span class="hljs-comment">// Import the ThemeProvider from your context file</span>
<span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'./Header'</span>;
<span class="hljs-keyword">import</span> MainContent <span class="hljs-keyword">from</span> <span class="hljs-string">'./MainContent'</span>;
<span class="hljs-keyword">import</span> Footer <span class="hljs-keyword">from</span> <span class="hljs-string">'./Footer'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeProvider</span>&gt;</span>
      {/* Wrap your entire application with the ThemeProvider */}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>
        <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span>
       <span class="hljs-attr">backgroundColor:</span> <span class="hljs-attr">theme</span> === <span class="hljs-string">'light'</span> ? '<span class="hljs-attr">white</span>' <span class="hljs-attr">:</span> '<span class="hljs-attr">black</span>',
       <span class="hljs-attr">color</span> <span class="hljs-attr">:</span> <span class="hljs-attr">theme</span> === <span class="hljs-string">'light'</span> ? '<span class="hljs-attr">black</span>' <span class="hljs-attr">:</span> '<span class="hljs-attr">white</span>',
}}
&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> /&gt;</span>
       <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeProvider</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p><strong>II)</strong> <code>ThemeContext.js</code><strong>:</strong> The <code>ThemeContext</code> file contains the <code>ThemeProvider</code>, where the theme state and <code>toggleTheme</code> function are defined. The theme context is created using the <code>createContext</code> function, and the <code>ThemeContext.Provider</code> wraps its children, which are the components that need access to the theme. Dont forget that first we will import our hooks from React. Here is the code below</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext, useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> ThemeContext = createContext();

<span class="hljs-keyword">const</span> ThemeProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);

  <span class="hljs-keyword">const</span> toggleTheme = <span class="hljs-function">() =&gt;</span> {
    setTheme(theme === <span class="hljs-string">'light'</span> ? <span class="hljs-string">'dark'</span> : <span class="hljs-string">'light'</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">theme</span>, <span class="hljs-attr">toggleTheme</span> }}&gt;</span>
      {children}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeContext.Provider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> { ThemeProvider, ThemeContext };
</code></pre>
<p><strong>III)</strong> <code>Header.js</code><strong>:</strong> This component displays the application header, including the title and a "Toggle Theme" button. It consumes the theme from the <code>ThemeContext</code> using the <code>useContext</code> hook.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { ThemeContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./ThemeContext'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { theme, toggleTheme } = useContext(ThemeContext);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span> &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'App-header'</span>&gt;</span> The Theme is {theme}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleTheme}</span>&gt;</span>Toggle Theme<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Header;
</code></pre>
<p><strong>IV)</strong> <code>App.css</code><strong>:</strong> Here is a basic CSS file for styling our project, you can always style it the way you want</p>
<pre><code class="lang-javascript">.App {
  text-align: center;
  font-family: Arial, sans-serif;
  transition: background-color <span class="hljs-number">0.3</span>s, color <span class="hljs-number">0.3</span>s;
   width : <span class="hljs-number">100</span>%;
   height : <span class="hljs-number">100</span>%;
}

.App-header {
  background-color: #<span class="hljs-number">282</span>c34;
  min-height: <span class="hljs-number">20</span>vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: <span class="hljs-number">100</span>px;
  color: white;
}
button {
  <span class="hljs-attr">padding</span>: <span class="hljs-number">10</span>px <span class="hljs-number">20</span>px;
  font-size: <span class="hljs-number">16</span>px;
  background-color: #<span class="hljs-number">61</span>dafb;
  border: none;
  cursor: pointer;
  margin-top: <span class="hljs-number">20</span>px;
}
</code></pre>
<p>Try this out and i am sure you will love the result, now let us look at a more complex example.</p>
<p>This more complex example showcases how the Context API can be used to manage user authentication across different components in a React application.</p>
<p>In this example, we have a more complex scenario with different components, please remember you can always style it the way you want with CSS. Lets take a look at the components:</p>
<ul>
<li><code>AuthApp.js</code> : wraps the entire application with the <code>AuthProvider</code> to provide user authentication capabilities to its child components.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { AuthProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'./AuthContext'</span>; <span class="hljs-comment">// Import the AuthProvider from your context file</span>
<span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">'./Home'</span>;
<span class="hljs-keyword">import</span> Profile <span class="hljs-keyword">from</span> <span class="hljs-string">'./Profile'</span>;
<span class="hljs-keyword">import</span> Login <span class="hljs-keyword">from</span> <span class="hljs-string">'./Login'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AuthApp</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AuthProvider</span>&gt;</span>
      {/* Wrap your entire application with the AuthProvider */}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Home</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Profile</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Login</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">AuthProvider</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> AuthApp;
</code></pre>
<ul>
<li><p><code>AuthContext.js</code>: contains the <code>AuthProvider</code>, managing user authentication and providing functions for login and logout. The <code>AuthContext</code> is created using the <code>createContext</code> function.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">import</span> React, { createContext, useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

  <span class="hljs-keyword">const</span> AuthContext = createContext();

  <span class="hljs-keyword">const</span> AuthProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>);
    <span class="hljs-keyword">const</span> [authenticated, setAuthenticated] = useState(<span class="hljs-literal">false</span>);

    <span class="hljs-keyword">const</span> login = <span class="hljs-function">(<span class="hljs-params">userData</span>) =&gt;</span> {
      setUser(userData);
      setAuthenticated(<span class="hljs-literal">true</span>);
    };

    <span class="hljs-keyword">const</span> logout = <span class="hljs-function">() =&gt;</span> {
      setUser(<span class="hljs-literal">null</span>);
      setAuthenticated(<span class="hljs-literal">false</span>);
    };

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AuthContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">user</span>, <span class="hljs-attr">authenticated</span>, <span class="hljs-attr">login</span>, <span class="hljs-attr">logout</span> }}&gt;</span>
        {children}
      <span class="hljs-tag">&lt;/<span class="hljs-name">AuthContext.Provider</span>&gt;</span></span>
    );
  };

  <span class="hljs-keyword">export</span> { AuthProvider, AuthContext };
</code></pre>
</li>
<li><p><code>Home.js</code>: represents the home page of the application and provides links to the profile and login pages.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"home"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to our App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/profile"</span>&gt;</span>Go to Profile<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/login"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
</li>
<li><p><code>Profile.js :</code>displays the user's profile information. It consumes the user and authentication status from the <code>AuthContext</code> and offers a logout button when the user is authenticated.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
  <span class="hljs-keyword">import</span> { AuthContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./AuthContext'</span>;
  <span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> {  authenticated, logout } = useContext(AuthContext);

    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"profile"</span>&gt;</span>
        {authenticated ? (
          <span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{logout}</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          <span class="hljs-tag">&lt;/&gt;</span></span>
        ) : (<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please log in to view your profile.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/login"</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
        )}
      &lt;/div&gt;
    );
  }

  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
</li>
</ul>
<p><code>Login.js</code>: is a component that allows users to log in. It collects and validates user input, and when the login is successful, it calls the <code>login</code> function provided by the <code>AuthContext</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { AuthContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./AuthContext'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Login</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">const</span> { login, authenticated } = useContext(AuthContext);

  <span class="hljs-keyword">const</span> handleLogin = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// In a real app, you would perform authentication here</span>
    <span class="hljs-keyword">const</span> userData = { username, <span class="hljs-attr">authenticated</span>: <span class="hljs-literal">true</span> };
    login(userData);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"login"</span>&gt;</span>
      {authenticated ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You are already logged in as {username}.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      ) : (
        <span class="hljs-tag">&lt;&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
            <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setUsername(e.target.value)}
          /&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span>
            <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setPassword(e.target.value)}
          /&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleLogin}</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
      )}
    &lt;/div&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Login;
</code></pre>
<h3 id="heading-7-conclusion"><strong>7. Conclusion</strong></h3>
<p>As we reach the end of this exploration of the React Context API, let's recap the key points discussed and some other key points you should know</p>
<ul>
<li><strong>Summary of key points:</strong></li>
</ul>
<p>- The Context API is a powerful tool in React for managing and sharing state across components without the need for excessive prop drilling.</p>
<p>- Context providers and consumers are the core components of the Context API. Providers establish the context and its initial state, while consumers access and use the provided context data.</p>
<p>- Creating and using context is a straightforward process, involving the <code>createContext</code> function, the `Provider` component, and the <code>useContext</code> hook or the Consumer component.</p>
<p>- Context values can be updated using various techniques, including state management, function props, reducers, or side effects like <code>useEffect</code>.</p>
<p>- Nested contexts enable you to manage multiple aspects of state efficiently, but careful structuring is essential to prevent conflicts and maintain performance.</p>
<p>- Optimizing context performance in large applications requires memoization, context splitting, lazy loading, and other strategies to minimize unnecessary re-renders.</p>
<p>- Best practices for using the Context API include isolating concerns with multiple contexts, opting for provider components with values, and designing contexts thoughtfully.</p>
<p>- To avoid common pitfalls, be cautious about excessive nesting, optimize value updates, and consider alternatives like local state or other state management libraries for specific use cases.</p>
<p>The Context API in React is a versatile tool that opens the door to efficient state management and data sharing. As you embark on your journey as a React developer, we encourage you to continue exploring and experimenting with Context API to uncover its full potential.</p>
<p>Experiment with different use cases, optimize performance, and refine your understanding of context-driven development. Dive deeper into related concepts like memoization, state management, and performance profiling to become a master of context-based state management in React.</p>
<p>Your exploration doesn't end here; it's merely the beginning of your journey to create efficient React applications. Happy coding, and may your applications thrive with the knowledge gained from this exploration of the Context API.</p>
<p>Thank you for reading, don't forget to leave a like and a comment you can check out more of my blog at <a target="_blank" href="https://tayo.hashnode.dev/">tayo.hashnode.dev</a></p>
]]></content:encoded></item><item><title><![CDATA[The basics of web development: A 
comprehensive guide for beginners]]></title><description><![CDATA[In today's world, web development is fast becoming a foundational skill that opens doors to a world of possibilities. Whether you're looking to establish your online presence, delve into the world of technology, or pursue a career in web development,...]]></description><link>https://tayo.hashnode.dev/the-basics-of-web-development-a-comprehensive-guide-for-beginners</link><guid isPermaLink="true">https://tayo.hashnode.dev/the-basics-of-web-development-a-comprehensive-guide-for-beginners</guid><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Abdulrahman Rufai]]></dc:creator><pubDate>Sun, 20 Aug 2023 17:38:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1692521839375/a26f6243-403a-4744-a35c-0ba778e8112f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today's world, web development is fast becoming a foundational skill that opens doors to a world of possibilities. Whether you're looking to establish your online presence, delve into the world of technology, or pursue a career in web development, understanding the fundamentals is the first step.  In this article, we will talk about the essential components of web development, from building the structural foundation using HTML to crafting stylish layouts with CSS and adding dynamic interactivity.</p>
<p>Whether you're new to coding or simply curious about web development, or thinking about transitioning into a tech career, this guide is tailored to equip you with the knowledge of web development and everything that entails it.</p>
<p>We will be looking into the following contents:</p>
<p><strong>1) The Core Components of Web Development:</strong></p>
<ul>
<li><p>HTML: The Structure of Web Pages</p>
</li>
<li><p>CSS: Styling and Design</p>
</li>
<li><p>JavaScript: Adding Interactivity</p>
</li>
</ul>
<p><strong>2) Setting Up Your Development Environment:</strong></p>
<ul>
<li>Text Editors and IDE</li>
</ul>
<p><strong>3) Front-End vs. Back-End Development:</strong></p>
<ul>
<li><p>Front-End Development</p>
</li>
<li><p>Back-End Development</p>
</li>
</ul>
<p><strong>4) Introduction to Frameworks and Libraries</strong>:</p>
<ul>
<li><p>Front-End Frameworks (e.g., React, Vue)</p>
</li>
<li><p>Back-End Frameworks (e.g., Express, Django)</p>
</li>
</ul>
<p><strong>5) Responsive Design and Mobile Compatibility</strong></p>
<p><strong>6) Basics of APIs and HTTP:</strong></p>
<ul>
<li><p>Introduction to APIs</p>
</li>
<li><p>Understanding HTTP</p>
</li>
</ul>
<p><strong>7) Version Control with Git and GitHub:</strong></p>
<ul>
<li><p>Git Basics</p>
</li>
<li><p>Collaborative Development with GitHub</p>
</li>
</ul>
<p><strong>8) Security Considerations in Web Development</strong></p>
<ul>
<li><p>Common Security Threats</p>
</li>
<li><p>Best practices for web security</p>
</li>
</ul>
<p><strong>9) Launching Your Website:</strong></p>
<ul>
<li>Launching and Monitoring</li>
</ul>
<p>Now, let's dive into it fully</p>
<h3 id="heading-1-the-core-components-of-web-development">1) <strong>The Core Components of Web Development</strong></h3>
<ul>
<li>HTML: The Structure of Web Pages:</li>
</ul>
<p>Hyper-Text Markup language(HTML) forms the backbone of every web page. HTML tags define the structure and content of a webpage, from headings and paragraphs to images and links. Tags are enclosed in angle brackets and are often used in pairs, with an opening tag(&lt;&gt;) and a closing tag(&lt;/&gt;).</p>
<p>To create a basic HTML page, you need only a few essential tags. The &lt;!DOCTYPE html&gt; declaration specifies the document type and version of HTML being used. The &lt;html&gt; tag is the root element, containing the &lt;head&gt; and &lt;body&gt; sections.</p>
<p>A basic HTML page will look like this:</p>
<pre><code class="lang-markdown"><span class="xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span></span>
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span></span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span></span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<ul>
<li>CSS: Styling and Design</li>
</ul>
<p>Cascading Style Sheet (CSS) is used to add visual appeal to HTML elements. With CSS, you can control properties like color, font size, spacing, and layout. Selectors are used to target specific HTML elements, and rules define how those elements should appear. Selectors can be based on element names, classes, IDs, and more. A basic CSS page will look like this</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">h1</span>{ 
<span class="hljs-attribute">color</span>: red; 
<span class="hljs-attribute">font-size</span>:medium;
}
</code></pre>
<ul>
<li>JavaScript: Adding Interactivity</li>
</ul>
<p>JavaScript is a programming language that adds interactivity and dynamic behavior to web pages. It enables you to create features like pop-up modals, form validation, and dynamic content updates without requiring a page refresh.</p>
<p>JavaScript can respond to user interactions like clicks and keystrokes. Event listeners allow you to "listen" for specific events and execute code in response.</p>
<h3 id="heading-2-setting-up-your-development-environment">2) <strong>Setting up your development environment:</strong></h3>
<ul>
<li>Text Editors and IDEs</li>
</ul>
<p>Choosing the Right Editor for You:</p>
<p>A text editor or integrated development environment (IDE) is where you'll write your code. Choose one that suits your preferences and needs. Some popular options include Visual Studio Code, Sublime Text, and Atom.</p>
<p>Visual Studio code is very popular and well-recommended.</p>
<p>A good development environment can significantly enhance your coding efficiency and overall experience.</p>
<p>Modern web browsers come with built-in developer tools that allow you to inspect HTML, CSS, and JavaScript. You can use these tools to troubleshoot issues, modify code on the fly, and analyze network activity.</p>
<p>Note:</p>
<p>It's important to test your web pages in multiple browsers to ensure they work correctly for all users. Browsers can interpret code differently.</p>
<h3 id="heading-3-front-end-vs-back-end-development"><strong>3) Front-End vs Back-End Development:</strong></h3>
<ul>
<li>Front-End Development</li>
</ul>
<p>Front-end developers focus on the user interface and user experience (UI/UX) of a website. They work with HTML, CSS, and JavaScript to create visually appealing and interactive web pages.</p>
<p>Front-end developers need to be proficient in HTML for structure, CSS for styling, and JavaScript for interactivity. They also often work with front-end libraries and frameworks to streamline development.</p>
<ul>
<li>Back-End Development</li>
</ul>
<p>Back-end developers handle the server-side logic and database operations of a website. They ensure that the website's data is stored, retrieved, and processed efficiently. While front-end development deals with the visual presentation and user experience, back-end development encompasses the server-side logic that powers the application.</p>
<p>Languages like PHP, Python, Ruby, and Node.js are commonly used for back-end development. Back-end developers build APIs, manage databases, and handle user authentication.</p>
<h3 id="heading-4introduction-to-frameworks-and-libraries"><strong>4)Introduction to Frameworks and Libraries</strong></h3>
<ul>
<li>Front-End Frameworks (e.g., React, Vue):</li>
</ul>
<p>Front-end frameworks like React and Vue provide pre-built components and a structured approach to building user interfaces. They enhance development speed and help maintain consistency across projects.</p>
<p>Getting Started with React:</p>
<p>To start with React, you'll need to set up a development environment, install the necessary dependencies, and create components. You can read more about setting up react at  <a target="_blank" href="https://tayo.hashnode.dev/how-to-installcreate-react-app-on-vs-code">https://tayo.hashnode.dev/how-to-installcreate-react-app-on-vs-code</a></p>
<ul>
<li>Back-End Frameworks (e.g., Express, Django)</li>
</ul>
<p>Streamlining Back-End Development:</p>
<p>Back-end frameworks are pre-built structures that streamline the development of server-side applications. They offer a set of tools, libraries, and conventions that facilitate the creation of complex functionality Back-end frameworks play a pivotal role in shaping the architecture and functionality of websites and applications. They simplify common tasks like routing, handling HTTP requests, and managing databases. They provide a foundation that helps developers focus on implementing features rather than dealing with low-level details.</p>
<h3 id="heading-5-responsive-design-and-mobile-compatibility"><strong>5) Responsive Design and Mobile Compatibility</strong></h3>
<p>Responsive design ensures that your website looks and functions well on various devices and screen sizes. With the proliferation of smartphones and tablets, catering to different devices is crucial for a positive user experience.</p>
<p>Use flexible grid systems, media queries, and viewport meta tags to create responsive layouts. Media queries allow you to apply different styles based on the device's characteristics, adapting your design accordingly.</p>
<h3 id="heading-6-basics-of-apis-and-http"><strong>6) Basics of APIs and HTTP</strong></h3>
<ul>
<li>Introduction to APIs</li>
</ul>
<p>What Are APIs?:</p>
<p>APIs (Application Programming Interfaces) allow different software applications to communicate with each other. They define how requests and responses should be structured.</p>
<p>APIs are used for retrieving data from a server (GET requests), sending data to a server (POST requests), and performing other operations like updating or deleting data and enabling data exchange between systems.</p>
<ul>
<li>Understanding HTTP</li>
</ul>
<p>Exploring the HTTP Protocol:</p>
<p>HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. It defines how clients (web browsers) and servers interact. HTTP methods like GET, POST, PUT, and DELETE dictate the type of request being made.</p>
<p>A typical HTTP request consists of a method (e.g., GET), a URL, headers, and an optional body. The server responds with a status code indicating the outcome of the request and a response body containing the requested data.</p>
<h3 id="heading-7-version-control-with-git-and-github"><strong>7) Version Control with Git and GitHub:</strong></h3>
<ul>
<li>Git Basics</li>
</ul>
<p>What Is Version Control?:</p>
<p>Version control allows you to track changes to your code over time. Git is a popular version control system that enables collaboration and helps you manage different versions of your codebase.</p>
<p>Basic Git commands include <code>git init</code> (initialize a repository), <code>git add</code> (stage changes), <code>git commit</code>(save changes), and <code>git push</code> (upload changes to a remote repository). The typical Git workflow involves creating branches.</p>
<ul>
<li>Collaborative Development with GitHub</li>
</ul>
<p>Setting Up a GitHub Repository:</p>
<p>GitHub is a platform for hosting and collaborating on Git repositories. You can create a repository, push your local code to it, and invite collaborators to contribute. Pull requests facilitate code review and merging changes.</p>
<h3 id="heading-8-security-considerations-in-web-development"><strong>8) Security Considerations in Web Development</strong></h3>
<ul>
<li>Common Security Threats</li>
</ul>
<p>Cross-Site Scripting (XSS):</p>
<p>XSS is a vulnerability that allows attackers to inject malicious scripts into web pages. This can lead to stealing sensitive user information or performing unauthorized actions.</p>
<p>SQL Injection and Other Vulnerabilities:</p>
<p>SQL injection occurs when attackers manipulate input fields to execute unauthorized SQL queries on a database. Other vulnerabilities include CSRF (Cross-Site Request Forgery) and security misconfigurations.</p>
<ul>
<li>Best Practices for Web Security</li>
</ul>
<p>To enhance security, use input validation and sanitization to prevent XSS and SQL injection attacks. Implement HTTPS for secure data transmission and regularly update libraries to patch vulnerabilities.</p>
<h3 id="heading-9-launching-your-website"><strong>9) Launching Your Website</strong></h3>
<ul>
<li>Launching and Monitoring</li>
</ul>
<p>Deploying to a Production Server:</p>
<p>Choose a hosting environment suitable for your project, such as a cloud provider or a dedicated server. Configure your server, set up security measures, and deploy your website using tools like Git or FTP.</p>
<p>Monitoring Site Performance and Uptime:</p>
<p>After deployment, monitor your website's performance and uptime using tools like Google Analytics and uptime monitoring services. Regularly analyze metrics to identify areas for improvement.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Now that you've gained a solid understanding and you're familiar with the basics of web development, consider diving deeper into front-end and back-end development, exploring advanced topics like responsive design, databases, and authentication. Online resources, tutorials, and hands-on projects are great ways to continue learning.</p>
<p>Remember that web development is a continuous learning process, and there's always more to explore and discover.</p>
<p>You can check out more of my articles at  <a target="_blank" href="https://tayo.hashnode.dev/">tayo.hasnode.dev</a></p>
]]></content:encoded></item><item><title><![CDATA[HOW TO CONSUME RESTful API USING FETCH API AND AXIOS INTO  REACT APP.]]></title><description><![CDATA[In the realm of modern web development, it is important to learn how to consume APIs to fetch data into your modern React application as a modern front-end web developer trying to build React applications.
In this guide, you'll learn how to use the 2...]]></description><link>https://tayo.hashnode.dev/how-to-consume-restful-api-using-fetch-api-and-axios-into-react-app</link><guid isPermaLink="true">https://tayo.hashnode.dev/how-to-consume-restful-api-using-fetch-api-and-axios-into-react-app</guid><category><![CDATA[React]]></category><category><![CDATA[API basics ]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Javascript library]]></category><dc:creator><![CDATA[Abdulrahman Rufai]]></dc:creator><pubDate>Sun, 20 Aug 2023 14:10:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1692478354003/07a94eb6-548b-4146-912b-e202de2768a2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the realm of modern web development, it is important to learn how to consume APIs to fetch data into your modern React application as a modern front-end web developer trying to build React applications.</p>
<p>In this guide, you'll learn how to use the 2 main methods of consuming REST APIs : the native Fetch API and the versatile Axios library. Whether you're a React newcomer or an experienced developer seeking to refine your API consumption skills, this guide will show you the various methods to effectively fetch and manage data from external sources.</p>
<p>We shall be looking into the following:</p>
<p>I) What is REST API</p>
<p>II) How to consume REST API</p>
<ul>
<li>Intro to React hooks, Fetch API and Axios</li>
</ul>
<p>III) Consume REST API using Fetch API with different requests (<code>GET</code> , <code>POST</code>,<code>DELETE</code>)</p>
<p>IV) Consume REST API using Axios with different methods (<code>GET</code> , <code>POST</code>,<code>DELETE</code>)</p>
<p>V) Comparison between Fetch API and axios</p>
<p>VI) Conclusion</p>
<p>Let's get into details</p>
<h3 id="heading-i-what-is-rest-api">I)           <strong>What is REST API:</strong></h3>
<p>Application Program Interface(API) is a software intermediary that allows two applications to talk to each other. They are an accessible way to extract and share data across to a server.</p>
<p>A REpresentational State Transfer (REST) API also called RESTful API is an architectural style that uses HTTP requests to access and use data from servers and endpoints.</p>
<p>When a request is made via a REST API, it sends a representation of the resource's current state to the requester or endpoint. This state can take the form of Javascript Object Notation(JSON), XML or HTML.</p>
<p>JSON is the most widely used format.</p>
<h3 id="heading-ii-how-to-consume-restful-api">II) <strong>How to consume RESTful API:</strong></h3>
<p>RESTful API can be consumed using 2 major methods which are Fetch(a browser in-built web API) and Axios(a promise-based HTTP client) with aid of React hooks. Let's briefly look into React hooks</p>
<p>A) <strong>React hooks</strong>:</p>
<p>React hooks are simple JavaScript functions that allow function components to have access to state and other React features. You can learn more about them on <a target="_blank" href="https://www.w3schools.com/REACT/DEFAULT.ASP">www.w3schools.com</a></p>
<p>The 2 major React hooks we would be using are the useState and useEffect hooks, to handle the state and side effect of fetching the API respectively.</p>
<ul>
<li><p><strong>useState hook</strong> : is a react hook used to manage state in functional components. We use it to store data that is returned when we request data, like this:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> [posts, setPosts] = useState([]);
</code></pre>
</li>
<li><p><strong>useEffect hook:</strong> Is a React hook used to manage side effects, for example; fetching APIs and setting data. We perform API requests within this hook. It can render immediately the application mounts or after a specific state is reached. This is the way it is used :</p>
<pre><code class="lang-javascript">  useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-comment">// the data fetching is done here </span>
  }, []);
  <span class="hljs-comment">// the array makes it render once</span>
</code></pre>
</li>
</ul>
<p>B) <strong>Intro to Fetch API and Axios:</strong></p>
<ul>
<li><p><strong>Fetch API</strong>: The Fetch API is a JavaScript built-in method for retrieving resources from a server or an API endpoint. With different requests e.g GET, POST, DELETE we can perform different functions with Fetch. The <code>fetch()</code> method requires an argument which is the URL or link to the resource we want to fetch, which will return a promise that we can handle with <code>.then()</code> for success and <code>.catch()</code> for failures and errors. A basic Fetch API request will look like this:</p>
<pre><code class="lang-javascript">  fetch( our URL goes <span class="hljs-keyword">in</span> here) {
              .then(response) =&gt; response.json()
              .then(data) =&gt; <span class="hljs-built_in">console</span>.log(data)
               .catch(error) =&gt; {<span class="hljs-built_in">console</span>.log(error)}
   }
</code></pre>
</li>
<li><p><strong>Axios</strong>: Axios is an HTTP client library based on promises that makes it simple to send asynchronous HTTP requests to REST endpoints. It is similar to Fetch but with less code. Axios has to be installed first in our terminal</p>
</li>
</ul>
<h3 id="heading-iii-consume-restful-api-using-fetch-api">III)      <strong>Consume RESTful API using Fetch API</strong>:</h3>
<p>There are different request that can be made and we will touch the GET, POST , DELETE requests. Let's look into the following subtopics:</p>
<ul>
<li><strong>How to perform GET request with Fetch API:</strong> We use the HTTP GET method to request data from an endpoint and you do not need to state GET, GET is default.</li>
</ul>
<p>With a basic fetch request, we get the response from the API then use <code>JSON.stringify()</code> function to convert it to string.</p>
<p>For the rest of this tutorial we'll be using the <a target="_blank" href="https://jsonplaceholder.typicode.com/posts">free online API JSONPlaceholder</a> to fetch posts into our application</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React,{ useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> [posts, setPosts] = useState([]);<span class="hljs-comment">//this local state is where we will store the data we retrievre from the API</span>
<span class="hljs-keyword">const</span> fetchPosts =<span class="hljs-function">() =&gt;</span> {
    fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts?_limit=4"</span>)<span class="hljs-comment">//this will return a response object</span>
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())<span class="hljs-comment">// we have to convert the response object to json() method</span>
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-comment">//this returns our actual data</span>
     setPosts(data)) <span class="hljs-comment">//then we send the data to our state</span>
}

useEffect(<span class="hljs-function">() =&gt;</span> {
    fetchPosts() <span class="hljs-comment">// this fetches the data for us as soon as the application loads</span>
},[]);<span class="hljs-comment">// the array will make it render only once</span>
</code></pre>
<ul>
<li><p><strong>How to perform POST request with Fetch API</strong>: You can use HTTP <code>POST</code> method to send data to the endpoint by adding additional method to hold the data which will include body and header. We embed the data in a JSON format(cause that is the format the server understands), we must stringify it, then send it to the server or endpoint.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> addPost = <span class="hljs-function">(<span class="hljs-params">title, body</span>) =&gt;</span> {
      fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>, {
          <span class="hljs-attr">method</span>:<span class="hljs-string">"POST"</span>,
          <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
              <span class="hljs-attr">title</span>: title,
              <span class="hljs-attr">body</span>: body,
              <span class="hljs-attr">userId</span>: <span class="hljs-built_in">Math</span>.random().toString(<span class="hljs-number">36</span>).slice(<span class="hljs-number">2</span>),
          }),
          <span class="hljs-attr">headers</span> : {
              <span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'application/json; charset=UTF-8'</span>,
          },
      })
          .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
          .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
               setPosts(<span class="hljs-function">(<span class="hljs-params">posts</span>) =&gt;</span> [data, ...posts])
      });
</code></pre>
</li>
<li><p><strong>How to perform DELETE request with Fetch API:</strong> You can use the HTTP DELETE method to remove data from an endpoint. Then use a filter method to remove it from the UI by filtering the id. Dont forget, we will have to declare the method we want to use, a DELETE request will look like this:</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> deletePost = <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
    fetch(<span class="hljs-string">`https://jsonplaceholder.typicode.com/posts/<span class="hljs-subst">${id}</span>`</span>, {
        <span class="hljs-attr">method</span>:<span class="hljs-string">"DELETE"</span>,

    }) 
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span>(response.status === <span class="hljs-number">200</span>){
            setPosts(
                posts.filter(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> {
                    <span class="hljs-keyword">return</span> post.id !== id;
                })
            )
        }
    })
}
</code></pre>
<ul>
<li><p><strong>How to use async and await In Fetch API</strong>: To use async, we can avoid the .then() chaining by using async/await . First call async in the function. Then when making a request, add the await syntax to wait for a response. In this section we will also see how to handle errors in the <a target="_blank" href="http://response.data">response.data</a> from the API using <code>try....catch</code> block.</p>
<p>  When we use async/await syntax, our code will look like this:</p>
<pre><code class="lang-javascript">
  <span class="hljs-comment">//GET request using Fetch API with async/await </span>
  <span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span>{ <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts?_limit=4"</span>);
      <span class="hljs-keyword">const</span> data = response.json();
       setPosts(data);} <span class="hljs-keyword">catch</span> (error) {
          <span class="hljs-built_in">console</span>.log(error)
       }
  }
  useEffect(<span class="hljs-function">() =&gt;</span> {
      fetchPosts()
  },[]);
   <span class="hljs-comment">//POST request using Fetch API with async/await </span>
  <span class="hljs-keyword">const</span> addPost = <span class="hljs-keyword">async</span> (title, body) =&gt; {
     <span class="hljs-keyword">try</span>{ <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>, {
          <span class="hljs-attr">method</span>:<span class="hljs-string">"POST"</span>,
          <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
              <span class="hljs-attr">title</span>: title,
              <span class="hljs-attr">body</span>: body,
              <span class="hljs-attr">userId</span>: <span class="hljs-built_in">Math</span>.random().toString(<span class="hljs-number">36</span>).slice(<span class="hljs-number">2</span>),
          }),
          <span class="hljs-attr">headers</span> : {
              <span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'application/json; charset=UTF-8'</span>,
          },
      })
          <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">await</span> response.json()

               setPosts(<span class="hljs-function">(<span class="hljs-params">prevPosts</span>) =&gt;</span> [data, ...prevPosts])
      } <span class="hljs-keyword">catch</span> (error) {
          <span class="hljs-built_in">console</span>.log (error)
      }
  }
  <span class="hljs-comment">//DELETE request using Fetch API with async/await </span>
  <span class="hljs-keyword">const</span> deletePost = <span class="hljs-keyword">async</span> (id) =&gt; {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://jsonplaceholder.typicode.com/posts/<span class="hljs-subst">${id}</span>`</span>, {
          <span class="hljs-attr">method</span>:<span class="hljs-string">"DELETE"</span>,
  }) 
      <span class="hljs-keyword">if</span>(response.status === <span class="hljs-number">200</span>){
              setPosts(
                  posts.filter(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> {
                      <span class="hljs-keyword">return</span> post.id !== id;
                  })
              )
          }
</code></pre>
</li>
</ul>
<p>if you notice, to use async and await we put our request in a var. Don't forget to put the await syntax in front of the <code>.fetch()</code> method.</p>
<h3 id="heading-iv-consume-rest-api-using-axios">IV )       <strong>Consume REST API using Axios</strong>:</h3>
<p>When consuming APIs using Axios, we have to look into the following subtopics</p>
<ul>
<li><strong>Installation of Axios using package or CDN</strong>:</li>
</ul>
<p>Axios is not built-in like Fetch API, so we will install the package by running the following command in our terminal</p>
<pre><code class="lang-plaintext">npm install axios
</code></pre>
<p>or use a CDN which is a link that links you directly to the Axios package. Then we create an instance using <code>.create()</code> and embed our URL link inside, this saves us from unnecessary repetition of our URL link, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>


<span class="hljs-keyword">const</span> client = axios.create({
      <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>
});
</code></pre>
<ul>
<li><p><strong>How to perform GET request with Axios API:</strong> We will use the instance we created earlier to perform GET request. Unlike Fetch API, we don't need to state the method, we just attach the method to the instance and get the response in JSON format by default. Don't forget that we will put it in a useEffect hook like this:</p>
<pre><code class="lang-javascript">  useEffect(<span class="hljs-function">() =&gt;</span> {
     client.get(<span class="hljs-string">'?_limit=10'</span>).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
         setPosts(response.data);
  });
  }, []);
  <span class="hljs-comment">//the '?_limit=10' specifies that the limit of the post should be 10</span>
</code></pre>
<p>  You can see that the code is shorter with Axios.</p>
</li>
<li><p><strong>How to perform POST request with Axios</strong>: It functions similarly to GET request but this time it is to send data to the endpoint and also include the method with an option to hold the data we're sending in.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> addPost = {title, body} =&gt; {
  client.post(<span class="hljs-string">''</span>, {
         <span class="hljs-attr">title</span>: title;
         body: body;
  })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
  setPosts(<span class="hljs-function">(<span class="hljs-params">posts</span>) =&gt;</span> [response.data, ...posts]);
</code></pre>
</li>
<li><p><strong>How to perform a DELETE request with Axios</strong>: it is similar to a DELETE request with fetch. We use the delete method, which gets the id and deletes it from the API, and use <code>filter()</code> method to delete it from the UI</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> deletePost = <span class="hljs-keyword">async</span> (id) =&gt; {
 <span class="hljs-keyword">await</span> client.delete(<span class="hljs-string">`<span class="hljs-subst">${id}</span>`</span>)
 setPosts(posts.filter(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> post.id !== id;
 }))
</code></pre>
<ul>
<li><strong>How to handle errors with Axios</strong>: To handle errors using Axios, we use the <code>.catch()</code> method after <code>.then()</code> method. For async and await, we use our <code>try</code> and <code>catch</code> block. We use it the same way we used it in Fetch API, but for the <code>try....catch</code> block, we do it like this:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> client.get(<span class="hljs-string">'?_limit=4'</span>);
     <span class="hljs-built_in">console</span>.log(response.data)    
    setPosts(response.data);
    } <span class="hljs-keyword">catch</span> (error) {<span class="hljs-built_in">console</span>.log(error)}
}
</code></pre>
<ul>
<li><strong>How to use async and await In Axios</strong>: It's similar to the way we use it in fetch, by putting async in front of the function and putting await too. Earlier we've seen how to make Axios requests using promise, this is the total code when we use async/await for our GET, POST, DELETE requests:</li>
</ul>
<pre><code class="lang-javascript">
<span class="hljs-comment">//DELETE with axios,async/await</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
<span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> client.get(<span class="hljs-string">'?_limit=4'</span>);
     <span class="hljs-built_in">console</span>.log(response.data)    
    setPosts(response.data);
    } <span class="hljs-keyword">catch</span> (error) {<span class="hljs-built_in">console</span>.log(error)}
    };
fetchPosts()
},[]);

 <span class="hljs-comment">//POST with axios,async/await</span>
<span class="hljs-keyword">const</span> addPost = <span class="hljs-keyword">async</span> (title, body) =&gt; {
    <span class="hljs-keyword">try</span>{
   <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> client.post(<span class="hljs-string">''</span>, {
        title,
        body
    }) 
    <span class="hljs-built_in">console</span>.log(response.data);
      setPosts(<span class="hljs-function">(<span class="hljs-params">prevPosts</span>) =&gt;</span> [response.data, ...prevPosts])}
     <span class="hljs-keyword">catch</span> (error){<span class="hljs-built_in">console</span>.log(error)}
    };

<span class="hljs-comment">//DELETE with axios,async/await</span>
<span class="hljs-keyword">const</span> deletePost = <span class="hljs-keyword">async</span> (id) =&gt; {
 <span class="hljs-keyword">await</span> client.delete(<span class="hljs-string">`<span class="hljs-subst">${id}</span>`</span>)
 setPosts(posts.filter(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> post.id !== id;
 }))
</code></pre>
<h3 id="heading-v-comparison-between-fetch-api-and-axios">V)       <strong>Comparison between Fetch API and Axios</strong>:</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>FETCH</td><td>AXIOS</td></tr>
</thead>
<tbody>
<tr>
<td>Fetch is in-built into modern browsers</td><td>Axios is a third-party package that is installed</td></tr>
<tr>
<td>Fetch does not allow canceling requests</td><td>Axios allows canceling requests and request timeout</td></tr>
<tr>
<td>Fetch is a light package</td><td>Axios is a heavier package</td></tr>
<tr>
<td>Fetch cannot intercept HTTP request</td><td>Axios has the ability to intercept HTTP request</td></tr>
<tr>
<td>Fetch uses more code</td><td>Axios uses lesser code and provides us with a cleaner and more efficient project</td></tr>
<tr>
<td>Fetch uses body property</td><td>Axios uses data property</td></tr>
<tr>
<td>Fetch does not support upload progress</td><td>Axios has built-in support for download progress</td></tr>
</tbody>
</table>
</div><h3 id="heading-vi-conclusion">VI)      <strong>Conclusion</strong>:</h3>
<p>Now that you've learnt how to consume APIs using Fetch and Axios methods, you'll now be able to consume APIs in a complex way for your project and build data-driven applications that can seamlessly communicate with the web making it easy for you to manipulate and build modern websites. Whichever approach you opt for, the core principles of working with APIs remain the same.</p>
<p>Thank you for joining us in this journey into the realm of API consumption.You can check out my blog page for more technical writing articles on <a target="_blank" href="https://tayo.hashnode.dev/">tayo.hasnode.dev</a></p>
]]></content:encoded></item><item><title><![CDATA[How To Install/create  React App On Vs Code]]></title><description><![CDATA[React or React.js is a popular JavaScript library used to create user interfaces. React is well known for its fast, efficient, easy to use, flexibility and good performance.
Instead of manipulating the browser's DOM directly, React creates a virtual ...]]></description><link>https://tayo.hashnode.dev/how-to-installcreate-react-app-on-vs-code</link><guid isPermaLink="true">https://tayo.hashnode.dev/how-to-installcreate-react-app-on-vs-code</guid><category><![CDATA[React]]></category><category><![CDATA[vscode]]></category><dc:creator><![CDATA[Abdulrahman Rufai]]></dc:creator><pubDate>Thu, 17 Aug 2023 19:12:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/UYsBCu9RP3Y/upload/062295eb2be3e808907806772d1cdb78.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>React or React.js is a popular JavaScript library used to create user interfaces. React is well known for its fast, efficient, easy to use, flexibility and good performance.</p>
<p>Instead of manipulating the browser's DOM directly, React creates a virtual DOM in memory, where it does all the necessary manipulating, before making the changes in the browser DOM, which is one main reason for its popularity.</p>
<p>To use this JavaScript library, you'll have to install it first or as it is called "create a react app".</p>
<p>So here is the step by step process :</p>
<ul>
<li><p>First, we install Node.js on your computer by downloading the install from Node.js official website <a target="_blank" href="https://nodejs.org">https://nodejs.org</a>. This will provide us with Node.js package manager (npm).</p>
</li>
<li><p>Next we will open our visual studio code(VS code) and go to the home page to start.</p>
</li>
<li><p>Then we go to our terminal in our menu bar click on it, then click on new terminal to open our terminal</p>
</li>
</ul>
<p>*Tip: To test that you have Node.js and npm correctly installed on your machine, you can type node --version and npm --version in a terminal or command prompt.</p>
<ul>
<li>When we have confirmed our npm is correctly installed, we will then proceed to create our react app by typing in our terminal :</li>
</ul>
<pre><code class="lang-markdown">npx create-react-app my-app
</code></pre>
<p>Where my-app is the folder for our application.</p>
<p>This may take a few minutes to create our react app and it's dependencies.</p>
<ul>
<li><p>Then, some packages and folders will be installed like public, src, package.json and others</p>
</li>
<li><p>Next, we will run our React application by navigating to the new folder in our terminal by typing cd my-app, this will take us to our folder ,then type npm start to start the web server and open the application in a browser, like this :</p>
<pre><code class="lang-plaintext">  cd my-app 
  npm start
</code></pre>
</li>
<li><p>You should see the React logo and a link to "Learn React" on <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> in your browser. We'll leave the web server running while we look at the application with VS Code.</p>
</li>
<li><p>Now our react app is installed and ready to use</p>
</li>
<li><p>If you look  in the my-react-app directory on the left-hand side, and you will find a src folder. Inside the src folder there is a file called App.js. You'll see some content inside , you can change the html content inside and it will reflect on our browser.</p>
</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>Creating a new React app in VS Code is an easy and straight forward process. By following the steps outlined in this tutorial, you can quickly create a new React app and start building projects with react.</p>
<p>To learn more about react , you can check out my articles at <a target="_blank" href="http://tayo.hashnode.dev">tayo.hashnode.dev</a></p>
]]></content:encoded></item></channel></rss>