<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Toby</title>
    <description>The latest articles on Forem by Toby (@oluwatrillions).</description>
    <link>https://forem.com/oluwatrillions</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F999972%2F805931c6-8587-48e7-9f0e-3dd078fe0ab1.jpg</url>
      <title>Forem: Toby</title>
      <link>https://forem.com/oluwatrillions</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/oluwatrillions"/>
    <language>en</language>
    <item>
      <title>React 19: The new updates</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Mon, 29 Jul 2024 03:42:56 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/react-19-the-new-updates-2k68</link>
      <guid>https://forem.com/oluwatrillions/react-19-the-new-updates-2k68</guid>
      <description>&lt;p&gt;This week, we will be talking about the new React 19 updates and hooks. Having gone through and using some of these new updates, I can only agree that it has simplified some of the rigorous activities developers go through when building apps, especially interactive form-related applications.&lt;/p&gt;

&lt;p&gt;Join me and let us explore some of these new updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React Compiler&lt;/strong&gt;: The &lt;strong&gt;React compiler picks your React code, translates it into a JavaScript code&lt;/strong&gt; for the browser, and manages the state of your component or User Interface. This singular action helps to optimize the performance of your application.&lt;/p&gt;

&lt;p&gt;If you are familiar with the useMemo hook, useCallback hook, and the React.Memo, you will understand that they help memoize (storing of values or functions for future uses) your components, so they don't have to re-render when there are no state changes. When there are changes in state, React re-renders the component in question, and its children, and when there are no changes in your code, the component stays as is keeping the previous memory, value and state in the component or hook for future uses; thereby optimizing the performance of your components. This is exactly what the React Compiler does automatically, without having to call any of the aforementioned hooks manually. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Form Actions&lt;/strong&gt;: One of the biggest advantages of using React is the &lt;em&gt;&lt;strong&gt;management and mutation of state&lt;/strong&gt;&lt;/em&gt;, and this mostly happens when we use &lt;em&gt;&lt;/em&gt; elements. Forms help us create and handle user interactivity more effectively.  &lt;/p&gt;

&lt;p&gt;With &lt;em&gt;form actions&lt;/em&gt;, you don't need event handlers like onSubmit and onChange to effect live mutation of data, instead we can pass an &lt;strong&gt;&lt;em&gt;action&lt;/em&gt;&lt;/strong&gt; prop to the &lt;/p&gt; element which receives a function that triggers the event.&lt;br&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myFunction = async (formData) =&amp;gt; {
  const [name, setName] = useState("")

  const updatedName = await nameChange(formData.get("name"))
     setName(updatedName)
}

&amp;lt;form action={myFunction}&amp;gt;
   &amp;lt;input type="name" 
          name="name" _// this is important to be able to get our data //_
   /&amp;gt;
   &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;With this approach, we don't need the application of &lt;em&gt;useState&lt;/em&gt; to mutate data through &lt;em&gt;event.target.value&lt;/em&gt;, Instead, in &lt;em&gt;myFunction&lt;/em&gt; we can get the mutated data through an argument.&lt;/p&gt;

&lt;p&gt;It means from the &lt;em&gt;&lt;/em&gt; element in our form, we have to set a name attribute. Using this method means we allow &lt;strong&gt;React&lt;/strong&gt; handle the form itself through the &lt;strong&gt;&lt;em&gt;Native React form Object&lt;/em&gt;&lt;/strong&gt; instead of manually changing state through event handlers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Server Components&lt;/strong&gt;: React 19 allows for components to be rendered on a server before bundling, in a separate environment from the client application or SSR server setup. The Server components are not the same as SSR (server side rendering), but a separate server environment in React Server Components.&lt;br&gt;
This feature allows for components to pre-render before time, thereby resulting in fast content displays and improved load time. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Metadata&lt;/strong&gt;: React 19 allows for a flexible metadata. Developers can manage the &lt;em&gt;title&lt;/em&gt;, &lt;em&gt;description&lt;/em&gt; and other &lt;em&gt;meta&lt;/em&gt; tags of individual components through the &lt;em&gt;DocumentHead&lt;/em&gt; component. This will help to improve SEO (Search Engine Optimization).&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Const AboutUs = () =&amp;gt; {
 return (
    &amp;lt;&amp;gt;
      &amp;lt;title&amp;gt;Learn more about our company&amp;lt;/title&amp;gt;
      &amp;lt;meta name="AboutUs" description="You can find us on ..." /&amp;gt;
      // content
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;React 19&lt;/strong&gt; has a series of &lt;strong&gt;new&lt;/strong&gt; hooks, some, new, others an improvement to existing hooks. Let's discuss about them below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The use() hook&lt;/strong&gt;: The use hook is an experimental API that can directly be used to read the value of a Promise or context within a component or hook (which is its only known limitation for now). &lt;br&gt;
The use hook is very versatile and can also be used in place of useEffect, as It can be used for asynchronous data fetching. This helps to &lt;br&gt;
achieve a neater and concise code block. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Caveat&lt;/strong&gt;: &lt;em&gt;It is not a replacement for useEffect&lt;/em&gt; because it still has its own limitations that _useEffect _will execute without limits.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {use} from "react"
const fetchData = async () =&amp;gt; {
    const response = await fetch("https://........");
    return response.json()
}

const userData = () =&amp;gt; {
    const user = use(fetchData());

        return (
    &amp;lt;div className='username'&amp;gt;{user.name}&amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;useActionState()&lt;/strong&gt;: This is a new hook that helps to manage state changes. It helps to manage pending state, error handling, and final&lt;br&gt;
state updates. The &lt;em&gt;useActionState _works like the _useReduce _in that it receives two(2) parameters: the function to be called when the form is submitted, and an _initialState&lt;/em&gt;, and it returns an array containing three(3)values: the state, which is now the current state if there is a mutation of state, a new action(formAction) that can be passed as a prop in our form component to call the server action, and _isPending _that returns a _boolean _value if or not the form is submitted.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useActionState } from "react";

async function incrementFunction(initialState, formData) {
  return initialState + 1;
}

function StatefulForm({}) {
  const [state, formAction, isPending] = useActionState(incrementFunction, 0);

  console.log(state);

  return (
    &amp;lt;form&amp;gt;
      &amp;lt;button formAction={formAction}&amp;gt;{state}&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;From this example, the &lt;em&gt;incrementFunction&lt;/em&gt; adds &lt;em&gt;1&lt;/em&gt; to the &lt;em&gt;state&lt;/em&gt; every time the &lt;em&gt;button&lt;/em&gt; is clicked. The &lt;em&gt;initialState&lt;/em&gt; being 0, and then increases to 1 at the first click of the button, thereby changing the &lt;em&gt;state&lt;/em&gt; to 1, and for every other click on the button adds 1 to the last state of the component.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useOptimistic() hook&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;This is a new hook that allows users to see the outcome of their action even before the pages load completely. The pages are optimistically rendered to the user even when the server is still in its data fetching mode.&lt;/p&gt;

&lt;p&gt;With the hope that data fetching will be successful, React displays the intended result to the client, and when data fetching fails, React reverts to the value of the &lt;em&gt;previous state&lt;/em&gt; in order not to display incorrect data. This singular action helps in a seamless and fast display of data thereby improving user experience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useFormStatus()&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;As the name implies, &lt;em&gt;useFormStatus&lt;/em&gt; gives us the status of our &lt;em&gt;form&lt;/em&gt; or &lt;em&gt;form fields&lt;/em&gt;. This hook does not take in any parameter, but it sure returns 4 objects: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;pending&lt;/em&gt;&lt;/strong&gt;: This returns a &lt;em&gt;boolean&lt;/em&gt; value: &lt;em&gt;true&lt;/em&gt; or &lt;em&gt;false&lt;/em&gt;. It returns &lt;em&gt;true&lt;/em&gt; when the form is submitting, and &lt;em&gt;false&lt;/em&gt; when the form is submitted.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;data&lt;/em&gt;&lt;/strong&gt;: When the form is successfully submitted, we can get the information of the user or object from the form field like this:&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(formData.get("name"))
(formData.get("address"))
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;method&lt;/em&gt;&lt;/strong&gt;: The default method of a form is &lt;em&gt;GET&lt;/em&gt;, unless stated otherwise. We can get the method of our form with &lt;em&gt;.method&lt;/em&gt;. When we are submitting a form, a string method property should be specified as a &lt;em&gt;POST&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;action&lt;/em&gt;&lt;/strong&gt;: This is a reference to the function that will be passed to the action prop in our &lt;em&gt;&lt;/em&gt; element. &lt;/p&gt;

&lt;p&gt;The &lt;em&gt;useFormStatus&lt;/em&gt; must always be called from a &lt;em&gt;&lt;/em&gt; element or a component that is rendered inside a &lt;em&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;There's quite a few more updates that I can't really write about, so you don't get bored having to read so much. You can click on the &lt;a href="https://react.dev/blog/2024/04/25/react-19" rel="noopener noreferrer"&gt;React Docs Website&lt;/a&gt; to check out some of the other updates. &lt;/p&gt;

&lt;p&gt;I hope you had a great time learning with me. &lt;/p&gt;

&lt;p&gt;Do well to follow me if you enjoyed my articles.&lt;/p&gt;

&lt;p&gt;Thanks, and have a great week ahead my friends.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>useMemo</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Thu, 20 Apr 2023 14:52:22 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/usememo-1ff8</link>
      <guid>https://forem.com/oluwatrillions/usememo-1ff8</guid>
      <description>&lt;p&gt;Optimizing your application to increase performance should be the goal of every developer. Like me, I know a lot of internet users would rather shut down their computers than deal with a slow website that takes too much time to load its contents. The performance of an application is one of the things that endear users of it.&lt;/p&gt;

&lt;p&gt;In today's tutorial, we will be discussing how to use React Hook to achieve a performance-driven application.&lt;/p&gt;

&lt;p&gt;In React, when we talk about performance-oriented applications, we talk about &lt;em&gt;useMemo&lt;/em&gt;. These hooks help us to &lt;em&gt;memoize&lt;/em&gt; values or functions so we don't get to repeat these operations thereby causing a re-rendering in our application. Now let's dive into each of these &lt;em&gt;hooks&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  useMemo
&lt;/h2&gt;

&lt;p&gt;This is the React hook that helps us improve the performance of our application. When the performance of an application improves, the speed improves alongside. useMemo &lt;em&gt;memoizes&lt;/em&gt; an application's operation. &lt;br&gt;
In this context, when an operation is performed, &lt;em&gt;useMemo&lt;/em&gt; stores the output or value of that operation, &lt;em&gt;caches&lt;/em&gt; it and returns the output whenever the same operation is performed again. Instead of having to repeat the operation, &lt;em&gt;useMemo&lt;/em&gt; just returns the output stored in the previous operation provided any of the values used in computing that operation does not change. This way, you don't have to repeat the operation over and over, thereby increasing the performance and speed of that application.&lt;/p&gt;

&lt;p&gt;As a storekeeper whose tradition is to take stock of goods after the close of work for the day. If at the end of the next business day, no good was sold or restocked, will you have to take another count or just use the previous day's numbers? Your guess is as good as mine; &lt;em&gt;use the previous day's numbers&lt;/em&gt;. That's the same thing &lt;em&gt;useMemo&lt;/em&gt; does for us. Instead of having to perform the operation all over, it presents the &lt;em&gt;previously stored output&lt;/em&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to use useMemo
&lt;/h2&gt;

&lt;p&gt;useMemo takes in two (2) arguments: the &lt;em&gt;function&lt;/em&gt; calculating the value that will be stored and the &lt;em&gt;dependencies&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useMemo} from 'react'

const memoValue = useMemo(memoFunction, dependencies)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;em&gt;memoFunction&lt;/em&gt; here is the function that will perform the operation whose output will be &lt;em&gt;cached&lt;/em&gt;. It has to be a pure function with no arguments. When the component first renders, the &lt;em&gt;memoFunction's&lt;/em&gt; output will return. On subsequent renders, if the &lt;em&gt;dependencies&lt;/em&gt; do not change, the initial output will keep returning, but once the &lt;em&gt;dependencies&lt;/em&gt; change, React will call &lt;em&gt;memoFunction&lt;/em&gt;, store the &lt;em&gt;output&lt;/em&gt; so it can be used later and then &lt;em&gt;return&lt;/em&gt; the output.&lt;/p&gt;

&lt;p&gt;The dependencies on the other hand are the variables, state or props used in the &lt;em&gt;memoFunction&lt;/em&gt;. These &lt;em&gt;dependencies&lt;/em&gt; are the values that make up the output of the &lt;em&gt;memoFunction&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example without useMemo
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from 'react'

const UsememoTutorial = () =&amp;gt; {

    const [input, setInput] = useState(0)

     const [counter, setCounter] = useState(0)

    const memoFunction = (input) =&amp;gt; {
        console.log("we are running a square root");
        return input * input
    }

    const memoValue = memoFunction(input)

    const count = (e) =&amp;gt; {
        setCounter(counter + 1)
    }
  return (
      &amp;lt;div&amp;gt;
          &amp;lt;input type='number' value={input} 
           onChange={(e) =&amp;gt; setInput(e.target.value)} /&amp;gt;
          &amp;lt;h3&amp;gt; Square root of your input is: {memoValue}&amp;lt;/h3&amp;gt;
          &amp;lt;hr /&amp;gt;
          &amp;lt;div&amp;gt;
              &amp;lt;h3&amp;gt;Counter count is: { counter}&amp;lt;/h3&amp;gt;
              &amp;lt;button onClick={count}&amp;gt;Counter&amp;lt;/button&amp;gt;
          &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default UsememoTutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have 2 states in our component. Also, in our function (memoFunction), we have a message that gets logged to the console whenever any of the states change. You can try the code and you'll see for yourself. Next, we will see what the reactions look like when we memoize our function.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example using useMemo
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useMemo, useState} from 'react'

const UsememoTutorial = () =&amp;gt; {

    const [input, setInput] = useState(0)

    const [counter, setCounter] = useState(0)

    const memoFunction = (input) =&amp;gt; {
        console.log("we are running a square root");
        return input * input
    }

    const memoValue = useMemo(() =&amp;gt; memoFunction(input), [input])

    const count = (e) =&amp;gt; {
        setCounter(counter + 1)
    }
  return (
      &amp;lt;div&amp;gt;
          &amp;lt;input type='number' value={input} 
           onChange={(e) =&amp;gt; setInput(e.target.value)} /&amp;gt;
          &amp;lt;h3&amp;gt; Square root of your input is: {memoValue}&amp;lt;/h3&amp;gt;
          &amp;lt;hr /&amp;gt;
          &amp;lt;div&amp;gt;
              &amp;lt;h3&amp;gt;Counter count is: { counter}&amp;lt;/h3&amp;gt;
              &amp;lt;button onClick={count}&amp;gt;Counter&amp;lt;/button&amp;gt;
          &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default UsememoTutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, there is a bit of a difference in the code. We memoized the function (&lt;em&gt;memoFunction&lt;/em&gt;) and used our input state as a dependency. The message in our console only gets logged when the input changes, and not when you click the button to increment the counter. &lt;/p&gt;

&lt;p&gt;I am sure you are thinking, this looks exactly like useEffect, but well maybe yes, but not entirely. I'll explain a better scenario where you'll see a whole lot of difference between useMemo and useEffect.&lt;/p&gt;

&lt;h2&gt;
  
  
  When to Use useMemo
&lt;/h2&gt;

&lt;p&gt;When you calculate the value of a variable or function, useMemo helps store up the output so you don't have to recalculate this same operation all over again when you have to. When you need this same value, it presents it to you. &lt;/p&gt;

&lt;p&gt;If you've read other articles on this topic, I'm sure you'd have come across, a lot of places where it was made mentioned as the hook for expensiveCalculations. What that means is useMemo is used to optimize the performance of your application when you are working on a large project. If the project is small, don't use it because you'd probably not see so much of an effect, but the effect, speed and performance are glare when on a large application.&lt;/p&gt;

&lt;p&gt;Imagine working on a social app that consumes resources at scale and where the application renders per second because of its large number of users. Leaving your application bare to re-render every second might lead to a performance problem that could crash the app. Memoizing the function responsible for this could be a great deal for the app to increase its performance level. &lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;useMemo helps you increase the performance and speed of your application. And it is most effective when it's being used on a large application; there the effect on your application is obvious compared to using it on just a few lines of code. It helps to eliminate having to repeat yourself by doing the same calculation over and over. It just presents you the output of the last render when all the values remain unchanged.&lt;/p&gt;

&lt;p&gt;Thanks for reading through even though I know it was a long read. Hope it was helpful and educative. &lt;/p&gt;

&lt;p&gt;Do have a great day.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>React Series: useReducer</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Sat, 15 Apr 2023 17:53:23 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/react-series-usereducer-1eh4</link>
      <guid>https://forem.com/oluwatrillions/react-series-usereducer-1eh4</guid>
      <description>&lt;p&gt;useState hook as we discussed in one part of the series, helps in handling state management. However, useState is used for simple state management. When the state gets complex, it becomes uneasy to manage and can get quite confusing. &lt;/p&gt;

&lt;p&gt;In useState, we all know that the &lt;em&gt;state&lt;/em&gt;, &lt;em&gt;callback&lt;/em&gt;, and &lt;em&gt;rendering&lt;/em&gt; are all in the body of the component. Now, imagine if we have to manage several &lt;em&gt;form input&lt;/em&gt; states in our React application with different logics for each, the component gets larger, bulky and error-prone. This type of situation can break our application at the slightest update or refactoring of code. This is when the &lt;em&gt;useReducer()&lt;/em&gt; hook comes to play.&lt;/p&gt;

&lt;p&gt;In this tutorial, I will elaborate on the &lt;em&gt;useReducer&lt;/em&gt; hook: what it does, how it works and other related questions that may pop up in your mind.&lt;/p&gt;

&lt;h2&gt;
  
  
  useReducer()
&lt;/h2&gt;

&lt;p&gt;useReducer is the hook that helps you add a &lt;em&gt;reducer&lt;/em&gt; to manage state in your component. Are you thinking "&lt;em&gt;What is a reducer _" ?. A _reducer&lt;/em&gt; is a function that helps you update the state. You don't get it still? Don't worry, we are in this together. As we dive deeper, you'll get a full understanding of this hook and the different concepts around it.&lt;/p&gt;

&lt;p&gt;The hook is just like the &lt;em&gt;useState()&lt;/em&gt; hook, only that it helps manage &lt;em&gt;complex state&lt;/em&gt; situations. When you have to manage several states, the &lt;em&gt;useReducer()&lt;/em&gt; offers a more robust environment to manage the logic of your state.&lt;/p&gt;

&lt;p&gt;While in &lt;em&gt;useState&lt;/em&gt;, the whole body of work: logic, rendering etc is lumped into the component, &lt;em&gt;useReducer&lt;/em&gt; offers a different playing field for each aspect of the component. With this, it's easier to read the code, manage the state and render the component. As we dive deeper into the course, you will understand it a bit further than it sounds now.&lt;/p&gt;

&lt;p&gt;Now, let's move on to the technicalities of our discussion.&lt;/p&gt;

&lt;h2&gt;
  
  
  Important Concepts to Note
&lt;/h2&gt;

&lt;p&gt;Honestly, you'll come across some concepts and words that may likely sound strange to you, but believe me, they aren't too difficult to grasp as they sound. You'll come across them in every step of your state management with &lt;em&gt;useReducer&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Like &lt;em&gt;useState()&lt;/em&gt; where you declare a state in an array. The first being the &lt;em&gt;initialState&lt;/em&gt; and the second being the &lt;em&gt;updater function&lt;/em&gt;.&lt;br&gt;
&lt;code&gt;const [state, setState] = useState("")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With &lt;em&gt;useReducer&lt;/em&gt;, it isn't much different. To declare a &lt;em&gt;reducer&lt;/em&gt;, you do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useReducer } from 'react'

const [state, dispatch] = useReducer(reducer, initialState)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's discuss these concepts and arguments.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;state&lt;/strong&gt;&lt;/em&gt;: This is the current state. It is where the &lt;em&gt;initialState&lt;/em&gt; is triggered at the first render.&lt;br&gt;
&lt;em&gt;&lt;strong&gt;dispatch&lt;/strong&gt;&lt;/em&gt;: This is the function that helps you update your current state from its &lt;em&gt;initialState&lt;/em&gt; to a new value.  It fires the action type that was declared for the update. Once this is done, the component re-renders as the state has been updated.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;reducer&lt;/em&gt;&lt;/strong&gt;: This is the reducer function that specifies how the state is updated. It takes in two arguments: &lt;em&gt;state&lt;/em&gt; and &lt;em&gt;action&lt;/em&gt;. The state is the current state in question while the action is the type of activity that will be performed to update the state. I know this is a bit hard to grasp, but I'll explain with a counter app for a better understanding.&lt;br&gt;
&lt;em&gt;&lt;strong&gt;initialState&lt;/strong&gt;&lt;/em&gt;: This is the initial state. It usually comes as an object holding the initial value of the state.&lt;/p&gt;

&lt;p&gt;Now, let me use a simple counter app to explain these concepts, as I do realize it wouldn't be easy to grasp without a visible example. Let's get into it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useReducer, useState } from 'react'

const initialState = 0
const reducer = (state, action) =&amp;gt; {
    switch (action) {
        case "add":
            return state + 1;
        case "subtract":
            return state - 1;
        case "reset":
            return initialState;
        default:
            throw new Error("Invalid action")
    }
};

const Test = () =&amp;gt; {
    const [state, dispatch] = useReducer(reducer, initialState)

  return (
     &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{state}&amp;lt;/h2&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch("add")}&amp;gt;
        add
      &amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch("subtract")}&amp;gt;
        subtract
      &amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch("reset")}&amp;gt;
        reset
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In our &lt;em&gt;counter app&lt;/em&gt;, we can see all the concepts and arguments I explained earlier in play. They all fit in one place or the other carrying out their function in making sure the app works as it should. &lt;/p&gt;

&lt;p&gt;Let's start from the top of the code.&lt;/p&gt;

&lt;p&gt;We can see the &lt;em&gt;initialState&lt;/em&gt; being initialized. In most cases, it usually comes as an object, but in our case, it is a number. It all depends on the type of state or operation you're trying to update. Instead of having to initialize the &lt;em&gt;initialState&lt;/em&gt; to a value of &lt;code&gt;0&lt;/code&gt; at the top of the code, this would work too;&lt;br&gt;
&lt;code&gt;const [state, dispatch] = useReducer(reducer, 0)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Next, the &lt;em&gt;reducer&lt;/em&gt; function. It took in two (2) arguments: &lt;em&gt;state&lt;/em&gt; and &lt;em&gt;action&lt;/em&gt;. The state being the &lt;em&gt;initialState&lt;/em&gt;, and the &lt;em&gt;action&lt;/em&gt; being the type of operation we intend on carrying out on our counter app. We can see several action types(add, subtract, reset) that we could carry out on the application. &lt;/p&gt;

&lt;p&gt;Then in the JSX, we can see the &lt;em&gt;dispatch&lt;/em&gt; rolling out our &lt;em&gt;action types&lt;/em&gt; in the button to update the state of our &lt;em&gt;counter&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;Now, I am going to refactor the code so you can choose what way to write it. It all depends on your choice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useReducer, useState } from 'react'

const initialState = {count:0}
const reducer = (state, action) =&amp;gt; {
    switch (action.type) {
        case "add":
            return {count: state.count + 1};
        case "subtract":
            return {count: state.count - 1};
        case "reset":
            return {count: initialState.count};
        default:
            throw new Error("Invalid action")
    }
};

const Test = () =&amp;gt; {
    const [state, dispatch] = useReducer(reducer, initialState)

  return (
     &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{state.count}&amp;lt;/h2&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: "add"})}&amp;gt;
        add
      &amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: "subtract"})}&amp;gt;
        subtract
      &amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: "reset"})}&amp;gt;
        reset
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can copy the code and try it out. It works just fine.&lt;/p&gt;

&lt;h2&gt;
  
  
  When to Use useReducer
&lt;/h2&gt;

&lt;p&gt;As I discussed at the beginning of the tutorial, &lt;em&gt;useReducer&lt;/em&gt; is best applicable when you have multiple or complex state situations. I will show an example of a form where we need to add a new user to our list of users. I'll show a &lt;em&gt;useState&lt;/em&gt; case and then apply the &lt;em&gt;useReducer&lt;/em&gt; case.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useEffect } from 'react'

const Test = () =&amp;gt; {

    const [name, setName] = useState("")
    const [age, setAge] = useState()
    const [address, setAddress] = useState("")
    const [occupation, setOccupation] = useState("")
    const [maritalStatus, setMaritalStatus] = useState("")

    const handleForm = (e) =&amp;gt; {
        e.preventDefault();
        setName(name)
        setAge(age)
        setAddress(address)
        setMaritalStatus(maritalStatus)
        setOccupation(occupation)
    }   
  return (
      &amp;lt;div&amp;gt;
          &amp;lt;form onClick={handleForm}&amp;gt;
              &amp;lt;h3&amp;gt;Employee Information&amp;lt;/h3&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='name'&amp;gt;Name&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' value={name} 
                   onChange={(e)=&amp;gt; setName(e.target.value)}/&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='age'&amp;gt;Age&amp;lt;/label&amp;gt;
                  &amp;lt;input type='number' value={age} 
                   onChange={(e)=&amp;gt; setAge(e.target.value)}/&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='address'&amp;gt;Address&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' value={address} 
                   onChange={(e)=&amp;gt; setAddress(e.target.value)}/&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='occupation'&amp;gt;Occupation&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' value={occupation} 
                   onChange={(e)=&amp;gt; setOccupation(e.target.value)}/&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='maritalStatus'&amp;gt;maritalStatus&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' value={maritalStatus} 
                   onChange={(e)=&amp;gt; setMaritalStatus(e.target.value)}/&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;button&amp;gt;SUBMIT&amp;lt;/button&amp;gt;
          &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a typical form using &lt;em&gt;useState&lt;/em&gt;. In this form, we have 5 state values that need to be updated. You can see how clogged the component is.&lt;/p&gt;

&lt;p&gt;Now we are going to use the &lt;em&gt;useReducer&lt;/em&gt; approach below to update our states, and you can have a clearer understanding of the slightest reason why this may be better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useEffect, useReducer } from 'react'

 const formState = {
        name: "",
        age: "",
        address: "",
        occupation: "",
        maritalStatus: ""
    }

    const employeeReducer = (state, action) =&amp;gt; {
        switch (action.type) {
            case "addNewName":
                return {
                    ...state, name: action.payload
                }
            case "addNewAge":
                return {
                    ...state, age: action.payload
                }
            case "addNewAddress":
                return {
                    ...state, address: action.payload
                }
            case "addNewOccupation":
                return {
                    ...state, occupation: action.payload
                }
            case "addNewMaritalStatus":
                return {
                    ...state, maritalStatus:action.payload
                }
            default:
                return state;
        }
    }

const Test = () =&amp;gt; {

    const [state, dispatch] = useReducer(employeeReducer, formState)

    const handleForm = (e) =&amp;gt; {
        e.preventDefault();
        console.log(state);
    };


  return (
      &amp;lt;div&amp;gt;
          &amp;lt;form&amp;gt;
              &amp;lt;h3&amp;gt;Employee Information&amp;lt;/h3&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='name'&amp;gt;Name&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' name='name' value={state.name}
                      onChange={(e) =&amp;gt; dispatch({type: "addNewName",             payload:e.target.value})} /&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='age'&amp;gt;Age&amp;lt;/label&amp;gt;
                  &amp;lt;input type='number' name='age' value={state.age}
                       onChange={(e) =&amp;gt; dispatch({type: "addNewAge", payload:e.target.value})} /&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='address'&amp;gt;Address&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' name='address' value={state.address}
                       onChange={(e) =&amp;gt; dispatch({type: "addNewAddress", payload:e.target.value})} /&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='occupation'&amp;gt;Occupation&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' name='occupation' value={state.occupation}
                       onChange={(e) =&amp;gt; dispatch({type: "addNewOccupation", payload:e.target.value})} /&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;div&amp;gt;
                  &amp;lt;label htmlFor='maritalStatus'&amp;gt;maritalStatus&amp;lt;/label&amp;gt;
                  &amp;lt;input type='text' name='maritalStatus' value={state.maritalStatus}
                       onChange={(e) =&amp;gt; dispatch({type: "addNewMaritalStatus", payload:e.target.value})} /&amp;gt;
              &amp;lt;/div&amp;gt;
              &amp;lt;button onClick={handleForm}&amp;gt;SUBMIT&amp;lt;/button&amp;gt;
          &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I know you are thinking this method is much bulkier than using &lt;em&gt;useState&lt;/em&gt;. Yes I agree, It's just an easier way to separate code into smaller chunks. There will arise times when you have to deal with much more state than these five and you'll find this method easier to update each state in real-time. &lt;/p&gt;

&lt;p&gt;If you find this tutorial helpful, don't forget to follow me and like it. There are other parts of the &lt;em&gt;React series&lt;/em&gt; on my page, you can go through them for your learning benefits.&lt;/p&gt;

&lt;p&gt;Have any questions? Feel free to hola at me.&lt;/p&gt;

&lt;p&gt;Please enjoy your weekend friends.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>react</category>
    </item>
    <item>
      <title>Context API and useContext</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Sun, 09 Apr 2023 13:00:00 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/context-api-and-usecontext-4430</link>
      <guid>https://forem.com/oluwatrillions/context-api-and-usecontext-4430</guid>
      <description>&lt;p&gt;&lt;em&gt;Props&lt;/em&gt; help you pass down data from parent to child components. By so doing, it's using the flow system of data passage (&lt;em&gt;top to bottom&lt;/em&gt;) to get that done. However, when the project grows, it becomes more complex using &lt;em&gt;props&lt;/em&gt; to pass down data from one component to another that is not directly a child of it, or where the said component is deeply nested in the application. &lt;/p&gt;

&lt;p&gt;Sometimes, the components in-between the parent and the child component may not need this information but they are obliged to pass it down until it gets to the component that needs it. This can be a heck of a problem and this is where you need the  &lt;em&gt;&lt;strong&gt;ContextAPI()&lt;/strong&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is ContextAPI
&lt;/h2&gt;

&lt;p&gt;The ContextAPI helps you pass &lt;em&gt;props&lt;/em&gt; or &lt;em&gt;state&lt;/em&gt; through the component tree without having to do it manually. It helps you pass information from the parent component to several other components in the application no matter how deeply nested they are. With &lt;em&gt;useContext&lt;/em&gt;, the information tunnels through from the parent component to the component that needs it through the use of context. It helps solve the &lt;em&gt;prop drilling&lt;/em&gt; problem encountered in React state management.&lt;/p&gt;

&lt;p&gt;Some types of data are too complex to be shared through props. Data such as &lt;em&gt;Auth&lt;/em&gt; and &lt;em&gt;theme&lt;/em&gt; can be passed through &lt;em&gt;context&lt;/em&gt; without compromising your application. &lt;br&gt;
&lt;em&gt;ContextAPI&lt;/em&gt; is an in-built React library so you don't need to bother about increasing your build size or having to install a third-party library.&lt;/p&gt;

&lt;p&gt;With &lt;em&gt;useContext&lt;/em&gt;, any component that needs information or prop from the parent component can easily ask for it and have access to it right away with the use of &lt;em&gt;context&lt;/em&gt;. &lt;/p&gt;
&lt;h2&gt;
  
  
  Prop-Drilling
&lt;/h2&gt;

&lt;p&gt;Prop-drilling is the process of passing props from a parent component down to child components no matter how deeply nested they are. The passing of data is done manually from component to component until the desired component is reached. &lt;/p&gt;

&lt;p&gt;Below is a diagram and an example of prop-drilling. &lt;/p&gt;

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

&lt;p&gt;In this diagram, the PARENT component (APP) is to pass state around down to as far as PLAYERIDENTITY component. Even though the DASHBOARD component doesn't have a need for this state, the data had to pass through it to get to the other children components: PLAYERSTATE and PLAYER. PLAYERSTATE consumed its share of state; &lt;em&gt;activeplayer&lt;/em&gt; and PLAYER component passed on the state to PLAYERSEX and PLAYERNAME even though it didn't have any use for them. PLAYERSEX received the &lt;em&gt;sex&lt;/em&gt; of the player and outputted it, and PLAYERNAME sent the last prop down to PLAYERIDENTITY.  &lt;/p&gt;

&lt;p&gt;Let's see this diagram in code, so you get to understand prop-drilling better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react'
import './App.css'
import Dashboard from './Dashboard'

function App() {

    const [sex, setSex] = useState('male')
    const [name, setName] = useState('Louisa')
    const [activePlayer, setActivePlayer] = useState('Yes')

  return (
      &amp;lt;div className="App"&amp;gt;
          &amp;lt;h3&amp;gt; Welcome {name}&amp;lt;/h3&amp;gt;
          &amp;lt;Dashboard {...{sex, name, activePlayer}} /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import PlayerState from './PlayerState'
import Player from './Player'

const Dashboard = ({sex, name, activePlayer}) =&amp;gt; {
    return (
        &amp;lt;div&amp;gt;
            &amp;lt;PlayerState {...{ activePlayer }} /&amp;gt;
            &amp;lt;Player {...{ sex, name }} /&amp;gt;
        &amp;lt;/div&amp;gt;
  )
}

export default Dashboard
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





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

const PlayerState = ({activePlayer}) =&amp;gt; {
  return (
      &amp;lt;div className='player-state'&amp;gt;
          &amp;lt;h4&amp;gt;Is the player active? { activePlayer}&amp;lt;/h4&amp;gt;
      &amp;lt;/div&amp;gt;
  )
}

export default PlayerState
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import PlayerSex from './PlayerSex'
import Playername from './Playername'

const Player = ({sex, name}) =&amp;gt; {
  return (
      &amp;lt;div className='player'&amp;gt;
          &amp;lt;PlayerSex {...{ sex }} /&amp;gt;
          &amp;lt;Playername {...{ name }} /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Player
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





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

const PlayerSex = ({sex}) =&amp;gt; {
  return (
      &amp;lt;div&amp;gt;Can you guess player sex? { sex}&amp;lt;/div&amp;gt;
  )
}

export default PlayerSex
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





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

const Playername = ({name}) =&amp;gt; {
  return (
      &amp;lt;div&amp;gt;
          &amp;lt;h3&amp;gt;Just one more chance to guess player name right&amp;lt;/h3&amp;gt;
          &amp;lt;PlayerIdentity {...{ name }} /&amp;gt;
        &amp;lt;/div&amp;gt;
  )
}

export default Playername
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





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

const PlayerIdentity = ({name}) =&amp;gt; {
  return (
      &amp;lt;div&amp;gt;{ name}&amp;lt;/div&amp;gt;
  )
}

export default PlayerIdentity
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This process can be tedious and any slight change of code or correction can break the application. Also, it is prone to errors such as a typo which can ruin the whole process.&lt;/p&gt;

&lt;p&gt;With &lt;em&gt;context&lt;/em&gt;, a lot of this stress can be done away with. Let's see how &lt;em&gt;useContext&lt;/em&gt; works.&lt;/p&gt;

&lt;h2&gt;
  
  
  The 3 Stages of useContext
&lt;/h2&gt;

&lt;p&gt;There are three (3) stages of &lt;em&gt;useContext&lt;/em&gt;.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;&lt;strong&gt;createContex&lt;/strong&gt;t&lt;/em&gt;: This is the stage where the &lt;em&gt;context&lt;/em&gt; is created using the &lt;em&gt;createContext()&lt;/em&gt; function. It receives only one argument called &lt;em&gt;defaultValue&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Provider&lt;/em&gt;&lt;/strong&gt;: This is a component of the &lt;em&gt;context&lt;/em&gt;. It is used to wrap all the components that need access to the information in the context. It receives a single &lt;em&gt;prop&lt;/em&gt; called &lt;em&gt;value&lt;/em&gt;. The value prop contains the value of your context (sounds like a tautology, but you will see what I mean later). All the components wrapped with the provider, and their children all have access to the value prop of the context.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Consumer: This is another component of the &lt;em&gt;context&lt;/em&gt;. It is used to wrap the components that will have access to the components. When the &lt;em&gt;Consumer&lt;/em&gt; is wrapped around a component, the value of the state can change, but when it's not, the value of the state remains the &lt;em&gt;defaultValue&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  How to use Context
&lt;/h2&gt;

&lt;p&gt;To use context, you have to create it with an &lt;em&gt;in-built function&lt;/em&gt; in the &lt;em&gt;useContext&lt;/em&gt; hook called &lt;em&gt;createContext&lt;/em&gt;. Now, let's create our context, and we will be using the same example we used in the &lt;em&gt;prop-drilling&lt;/em&gt; example but now using the useContext concept.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { createContext } from 'react'

export const MyContext = createContext();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, this is the first stage of the solution of our code. Next, we will wrap our &lt;em&gt;App&lt;/em&gt; component with the &lt;em&gt;context&lt;/em&gt; we just created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useContext, useState } from 'react'
import './App.css'
import Dashboard from './Dashboard'
import { MyContext } from './Context'

function App() {

     const [sex, setSex] = useState('male')
     const [name, setName] = useState('Louisa')
     const [activePlayer, setActivePlayer] = useState('Yes')   

  return (
      &amp;lt;div className="App"&amp;gt;
          &amp;lt;MyContext.Provider value={{
              sex, setSex, name, setName, activePlayer, setActivePlayer
          }}&amp;gt;
              &amp;lt;h3&amp;gt; Welcome {name}&amp;lt;/h3&amp;gt;
                &amp;lt;Dashboard /&amp;gt;
          &amp;lt;/MyContext.Provider&amp;gt;

    &amp;lt;/div&amp;gt;
  )
}

export default App
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we wrapped the &lt;em&gt;App&lt;/em&gt; being the parent component with our context &lt;em&gt;MyContext.Provider&lt;/em&gt;. With this, all the components in the application have access to the &lt;em&gt;value&lt;/em&gt; prop we set.&lt;/p&gt;

&lt;p&gt;Now, let's see the rest of the code. You will realize they aren't as large as they were while &lt;em&gt;prop-drilling&lt;/em&gt;. Now, they are lightweight and much more readable while still giving the same result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from 'react'
import { MyContext } from './Context'

const PlayerState = () =&amp;gt; {

    const playerStatus = useContext(MyContext)

  return (
      &amp;lt;div className='player-state'&amp;gt;
          &amp;lt;h4&amp;gt;Is the player active? { playerStatus.activePlayer}&amp;lt;/h4&amp;gt;
      &amp;lt;/div&amp;gt;
  )
}

export default PlayerState

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

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from 'react'
import { MyContext } from './Context'

const PlayerSex = () =&amp;gt; {

    const playerSex = useContext(MyContext)

  return (
      &amp;lt;div&amp;gt;Can you guess player sex? { playerSex.sex}&amp;lt;/div&amp;gt;
  )
}

export default PlayerSex
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useContext } from 'react'
import { MyContext } from './Context'

const PlayerState = ({ activePlayer }) =&amp;gt; {

    const playerStatus = useContext(MyContext)

  return (
      &amp;lt;div className='player-state'&amp;gt;
          &amp;lt;h4&amp;gt;Is the player active? { playerStatus.activePlayer}&amp;lt;/h4&amp;gt;
      &amp;lt;/div&amp;gt;
  )
}

export default PlayerState
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To be able to output our JSX, we first name a variable, then call our &lt;em&gt;context&lt;/em&gt; using the _useContex_t hook. Then we can render using our variable and call on the state.&lt;/p&gt;

&lt;p&gt;Now, these are all the components we need because we didn't have to pass the &lt;em&gt;props&lt;/em&gt; through every component manually to get to our desired component. &lt;/p&gt;

&lt;p&gt;If this was helpful, do well to follow me. And if you have questions, hola at me in the comment section.&lt;/p&gt;

&lt;p&gt;Have a great weekend my friends.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>react</category>
    </item>
    <item>
      <title>React Series: useRef Hook</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Thu, 06 Apr 2023 20:57:59 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/react-series-useref-hook-29m8</link>
      <guid>https://forem.com/oluwatrillions/react-series-useref-hook-29m8</guid>
      <description>&lt;p&gt;If you want to update the value of an element in your component or access any DOM elements, then the useRef() hook is your go-to. When updating state using useState, the component re-renders every time the state is accessed but using useRef, you can be guaranteed that would not occur.&lt;/p&gt;

&lt;h2&gt;
  
  
  Initializing useRef
&lt;/h2&gt;

&lt;p&gt;useRef hook is first initialized onto a variable that will perform the mutation. It accepts only one argument and returns a &lt;em&gt;reference&lt;/em&gt;. The reference is then accessed through a &lt;em&gt;ref&lt;/em&gt; keyword in the element where the mutation will take place. Let's see how to initialize a useRef.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef } from 'react'

const Test = () =&amp;gt; {

    const inputRef = useRef()

  return (
      &amp;lt;div&amp;gt;Test&amp;lt;/div&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, &lt;em&gt;inputRef&lt;/em&gt; is the variable where our &lt;em&gt;ref&lt;/em&gt; will be hooked onto in the return JSX. &lt;/p&gt;

&lt;h2&gt;
  
  
  Important Points to Note About useRef
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;It takes in only one initialvalue.The value can be of any type and it is ignore after the initial render.&lt;/li&gt;
&lt;li&gt;It returns a reference object that we refer to with the ref keyword in our JSX.&lt;/li&gt;
&lt;li&gt;The value of the reference is mutable.&lt;/li&gt;
&lt;li&gt;Updating a reference doesn't re-render the component.&lt;/li&gt;
&lt;li&gt;The value of the reference is persistent even when the component re-renders.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The &lt;em&gt;ref.current&lt;/em&gt; Property.
&lt;/h2&gt;

&lt;p&gt;The &lt;em&gt;ref&lt;/em&gt; object returned in useRef is mutable and contains one property called the &lt;em&gt;.current&lt;/em&gt;. The &lt;em&gt;current&lt;/em&gt; property is where all the actions in our &lt;em&gt;ref&lt;/em&gt; object take place. It gives you all the access to the DOM properties of the element you are making a reference to. Let's see some of the properties of .current. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The _current _property is what helps you mutate the value of your reference.&lt;/li&gt;
&lt;li&gt;With the &lt;em&gt;ref.current.contains&lt;/em&gt;, you can check if the element you are referencing passes a test. It's just like using &lt;em&gt;(variableName).contains&lt;/em&gt; in your string variable while working on arrays.&lt;/li&gt;
&lt;li&gt;With the &lt;em&gt;ref.current.focus&lt;/em&gt;, you can move the &lt;em&gt;focus&lt;/em&gt; of the mouse to a particular element. If you have an application where users need to enter their username before logging in, you can set the focus on the &lt;em&gt;username&lt;/em&gt; input box as soon as the application loads.&lt;/li&gt;
&lt;li&gt;You can change or &lt;em&gt;re-assign&lt;/em&gt; the value of your reference or state with the &lt;em&gt;ref.current.value&lt;/em&gt; property.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now let's see another code example where we will perform a small exercise referencing all the points we mentioned.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Test = () =&amp;gt; {

    const inputRef = useRef()

    const refExample = () =&amp;gt; {
        const name = inputRef.current
        inputRef.current = 'My name is Michael'
        console.log(inputRef.current);
    }

  return (
      &amp;lt;div&amp;gt;
          &amp;lt;input type='text' ref={inputRef} /&amp;gt;
          &amp;lt;button onClick={refExample}&amp;gt;Click me&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
// My name is Michael.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are using useRef to update the value of our &lt;em&gt;input&lt;/em&gt; element. After creating the &lt;em&gt;inputRef&lt;/em&gt; reference, we hooked it on to the &lt;em&gt;input&lt;/em&gt; element in our JSX. Then we created a &lt;em&gt;callback function&lt;/em&gt; where we updated the value of our reference and logged it to the console. The callback is what we are returning in the &lt;em&gt;button&lt;/em&gt; element.&lt;br&gt;
Please run the code and click on the button and you'd see the output.&lt;/p&gt;
&lt;h2&gt;
  
  
  Using useRef to Access The DOM.
&lt;/h2&gt;

&lt;p&gt;This is one of my favorite ways to use useRef. It can help you access some DOM methods and properties. Once you use the &lt;em&gt;.current&lt;/em&gt; property on the &lt;em&gt;ref&lt;/em&gt;, it gives you access to some properties that make your application robust.&lt;/p&gt;

&lt;p&gt;In this example, I will be using the &lt;em&gt;ref&lt;/em&gt; object to output an error in my input element. Let's see how that works.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useRef, useState } from 'react'

const Test = () =&amp;gt; {
    const [name, setName] = useState("")
    const errorRef = useRef()

    console.log(name.length);

    const handleBtn = (e) =&amp;gt; {
        if (!name) {
            const nameError = errorRef.current
            errorRef.current.textContent = "Please enter a name"
        } else {
            console.log(name);
        }
   }

  return (
      &amp;lt;&amp;gt;
          &amp;lt;div&amp;gt;
              &amp;lt;h3 ref={errorRef}&amp;gt;&amp;lt;/h3&amp;gt;
              &amp;lt;input type='text' 
                     value={name} 
                     onChange={((e)=&amp;gt; setName(e.target.value))}/&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;button onClick={handleBtn}&amp;gt;Click me&amp;lt;/button&amp;gt;
    &amp;lt;/&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, after setting the ref object to &lt;em&gt;errorRef&lt;/em&gt;, it was hooked to the &lt;em&gt;h3&lt;/em&gt; in the input element. We then created a &lt;em&gt;handleBtn&lt;/em&gt; function that checks if the user entered a value in the input box. If there is no value in the input box and the button was clicked, the &lt;em&gt;errorRef&lt;/em&gt; will output "&lt;em&gt;Please enter a name&lt;/em&gt;" to prompt the user to enter a value. if there is a name, it returns.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using useRef to Focus on an Element
&lt;/h2&gt;

&lt;p&gt;This is another beautiful use for useRef. I guess I mentioned it among the important notes. useRef can be used to &lt;em&gt;focus&lt;/em&gt; on important elements on your application. The elements could be username or email input boxes, and they can also be important elements on a form. Let's see how to use if for focus.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect, useRef} from 'react'

const Test = () =&amp;gt; {
    const focusRef = useRef()

    useEffect(() =&amp;gt; {
        focusRef.current.focus()
    })
  return (
      &amp;lt;&amp;gt;
          &amp;lt;div&amp;gt;
              &amp;lt;input type='text' ref={focusRef}/&amp;gt;
          &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, our ref which is &lt;em&gt;focusRef&lt;/em&gt; was used in a &lt;em&gt;useEffect&lt;/em&gt;, so that once the application loads, the focus of the typing cursor will be on the &lt;em&gt;input&lt;/em&gt; element. Please try the code out and you'll see for yourself. &lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;The value referenced in your &lt;em&gt;ref&lt;/em&gt; object will be &lt;em&gt;persistent&lt;/em&gt; for the full &lt;em&gt;lifecycle&lt;/em&gt; of the component.&lt;/p&gt;

&lt;p&gt;Like in one of the examples, the &lt;em&gt;ref&lt;/em&gt; will give you access to some &lt;em&gt;DOM nodes&lt;/em&gt;. In our case, we were able to access &lt;em&gt;textContent&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;useRef dos not &lt;em&gt;re-render&lt;/em&gt; when the value of the &lt;em&gt;ref&lt;/em&gt; is updated.&lt;/p&gt;

&lt;p&gt;I hope this tutorial was helpful. Don't forget to ask me questions if you are confused about anything.&lt;/p&gt;

&lt;p&gt;Please like and follow me if you think it's worth it.&lt;/p&gt;

&lt;p&gt;Have a great day folks.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>React Series: useEffect</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Sun, 02 Apr 2023 16:44:37 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/react-series-useeffect-43ki</link>
      <guid>https://forem.com/oluwatrillions/react-series-useeffect-43ki</guid>
      <description>&lt;p&gt;Welcome back to our React Series. I want to believe you had a good grasp of the &lt;em&gt;useState&lt;/em&gt; hook in the last class. There is so much more hooks will do for you, and I believe as you continue with this series, you will learn a lot more about them. Today we are moving on to another important hook that you will always come across in your journey in React, and that is the &lt;em&gt;useEffect&lt;/em&gt; hook. &lt;/p&gt;

&lt;h2&gt;
  
  
  What is useEffect hook?
&lt;/h2&gt;

&lt;p&gt;According to the React documentation, the useEffect hook was developed to eliminate some of the challenges posed by the life cycle methods of ES6 class components. The main challenge being &lt;em&gt;&lt;strong&gt;handling side-effects&lt;/strong&gt;&lt;/em&gt;. When you create an application that updates user information at every click or a timer app using &lt;em&gt;setTimeout()&lt;/em&gt;, this can lead to some unwanted side-effects, and that's one use-case for useEffect.&lt;/p&gt;

&lt;p&gt;Using useEffect is understanding the lifecycle of a component. A component's lifecycle is in three stages: &lt;em&gt;componentDidMount&lt;/em&gt;, &lt;em&gt;componentDidUpdate&lt;/em&gt; and &lt;em&gt;componentWillUnmount&lt;/em&gt;. Albeit, using these lifecycle methods is a class component feature. They cannot be used in a &lt;em&gt;functional component&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;useEffect is a combination of React's lifecycle methods. It helps you eliminate the repetition of code, and groups related code in one code block in a functional component. With &lt;em&gt;useEffect&lt;/em&gt;, you can do so much with writing so little.&lt;/p&gt;

&lt;h2&gt;
  
  
  Important concepts about useEffect
&lt;/h2&gt;

&lt;p&gt;It handles side-effects.&lt;br&gt;
It takes in 2 parameters: a callback and dependencies.&lt;br&gt;
The dependency array can take in more than one variable.&lt;br&gt;
Effects automatically run after every re-render, except you handle it in your dependencies.&lt;br&gt;
If handled in the dependency, effects run only when there is a change in the state of the dependency.&lt;br&gt;
If not handled well, side-effects can have damaging effects on your program or code.&lt;br&gt;
It helps you recognize the relevant part of the code after first render.&lt;/p&gt;
&lt;h2&gt;
  
  
  What are side-effects?
&lt;/h2&gt;

&lt;p&gt;These are actions performed outside of our React component in the component. These actions can indirectly change the returned output of our React component. Usually, the output of a component should be determined by the &lt;em&gt;props&lt;/em&gt; or &lt;em&gt;state&lt;/em&gt;. Side-effects are used to communicate with elements outside of the component. These elements can be APIs for data fetching, manually changing the DOM, timer functions like &lt;em&gt;setTimeout&lt;/em&gt;, window objects etc.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to use useEffect
&lt;/h2&gt;

&lt;p&gt;At this point, I believe you already have some sort of insight as to the use of useEffect. Now, we will be moving on how to write your first &lt;em&gt;useEffect&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;As I mentioned in the earlier point stated above, useEffect takes in two (2) arguments: a &lt;em&gt;callback function&lt;/em&gt; and a &lt;em&gt;dependency array&lt;/em&gt;. Let's see what that looks like in the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react'

useEffect((callback) =&amp;gt; {
    //function that runs every time there is a re-render.
}, [dependency array])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Typically, this is how to write your useEffect. Takes in two (2) arguments: the &lt;em&gt;callback function&lt;/em&gt; and the &lt;em&gt;dependency array&lt;/em&gt;. If there is any type of change in the dependency variables, the callback function runs automatically. The dependency array could be a &lt;em&gt;variable&lt;/em&gt;, &lt;em&gt;prop&lt;/em&gt; or some kind of &lt;em&gt;state&lt;/em&gt;. Also, the dependency array could contain more than one item. It can take in as many variables as possible.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useEffect With An Empty Depencendy Variable&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react'

useEffect((callback) =&amp;gt; {
    //function that runs every time there is a re-render.
}, [])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the dependency variable is empty, the callback function runs only once, and that is when the component renders for the first time. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useEffect Without a Dependency Array&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;When the dependency array is not included in the useEffect, the function for the side-effect runs every time there is a re-render. Doing this might lead to multiple re-renderings and that may be bad for your program.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react'

useEffect((callback) =&amp;gt; {
    //function that runs every time there is a re-render.
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Cleanup Function in useEffect?
&lt;/h2&gt;

&lt;p&gt;We sometimes need to stop the side-effect from running in a program. If for example, we have a timer function using &lt;em&gt;setInterval&lt;/em&gt;, the function will keep running until we stop the function using &lt;em&gt;clearInterval&lt;/em&gt;. Another example can be subscriptions that need to be stopped when they are no longer required. Cleanup function allows us to stop side-effects that no longer need to be run. &lt;/p&gt;

&lt;p&gt;If for example we set state using &lt;em&gt;setInterval&lt;/em&gt; and the function was not cleaned up. When the component is abandoned or no longer in use, the setInterval function will keep running and it will try to update the state even though it no longer exists. That is what we call &lt;em&gt;Memory Leak&lt;/em&gt;. An example is in the code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState, useEffect} from 'react'

const Test = () =&amp;gt; {

  const [time, setTime] = useState(0);

  useEffect(() =&amp;gt; {
    setInterval(() =&amp;gt; setTime(time + 1), 5000); 
      console.log(time);
  }, []);
}

export default Test

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

&lt;/div&gt;



&lt;p&gt;The above code is to update by 1 every 5 seconds. Even when we abandon the component and don't use it again, under the hood, it will keep incrementing, and that's because we didn't do a cleanup which may eventually cause a problem in our application.&lt;/p&gt;

&lt;p&gt;To &lt;em&gt;cleanup&lt;/em&gt; our timer function, we will create a &lt;em&gt;clearInterval function&lt;/em&gt; under the callback. This &lt;em&gt;clearInterval&lt;/em&gt; function will cleanup the side-effect every time our timer function runs. Let's see the code below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; import React, {useState, useEffect} from 'react'

const Test = () =&amp;gt; {

  const [time, setTime] = useState(0);

  useEffect(() =&amp;gt; {
    let interval = setInterval(() =&amp;gt; setTime(time + 1), 5000); 

    return () =&amp;gt; {
      // setInterval is cleared when component unmounts
      clearInterval(interval);
    }
  }, []);
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this &lt;em&gt;cleanup function&lt;/em&gt;, we are guaranteed that this component can do no damage to our application, because once the component unmounts, the side-effect stops updating. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;:&lt;br&gt;
You do not need the cleanup function for every side-effect. You only use it for certain components that update every time like a timer function, subscription etc. &lt;/p&gt;

&lt;p&gt;I really hope this was helpful. If you have any questions, please feel free to ask me anytime. Also, don’t forget to follow me and like this tutorial.&lt;/p&gt;

&lt;p&gt;Thanks and have a great weekend.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>React Hooks: useState</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Wed, 29 Mar 2023 14:47:09 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/react-hooks-usestate-o4k</link>
      <guid>https://forem.com/oluwatrillions/react-hooks-usestate-o4k</guid>
      <description>&lt;p&gt;React Hooks are the special functions that let us tap into React features in a functional component. As we all know, React is a powerful library that lets us build fast and reusable user interfaces. These interfaces have special features that we couldn't have access to in a functional component, hence the advent of Hooks.&lt;/p&gt;

&lt;p&gt;Hooks are JavaScript functions used in React as components. You cannot use Hooks in Vanilla JavaScript, and neither can you use them in class-based components. Hooks can only be used in a React Functional Component. State in Hooks can be of any data type: object, array, null, string, number etc, unlike in classes where the data type has to be an object. Now, let's get to the Hook of the day; useState.&lt;/p&gt;

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

&lt;p&gt;useState is the hook that helps you add and manage the state in a React application. It consists of a destructured pair of values where the first value is the current state of the variable, while the second is the updater function. In classes, you can use this.state to update the state of a function, but in React function component, you use useState to do the same job. useState makes state easier to understand access.&lt;/p&gt;

&lt;p&gt;useState is the most used Hook out there, and also the simplest of all the Hooks. Unlike JavaScript where you have to manually grab the HTML element you want to update, useState does that for you. State is kept inside a hook and accessed from the component where you call the hook; what this means is you can only call the hook inside the component where it was created, and not outside of it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Rules of using useState
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Always follow the pascalCase naming convention when naming your variables.&lt;/li&gt;
&lt;li&gt;Always make sure your second variable starts with set.&lt;/li&gt;
&lt;li&gt;State can be of any data type.&lt;/li&gt;
&lt;li&gt;Only use hooks in a function component.&lt;/li&gt;
&lt;li&gt;Never directly mutate state.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Why useState?
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;You don't have to manually update state.&lt;/li&gt;
&lt;li&gt;When the state updates, the page does not refresh, unlike vanilla JavaScript.&lt;/li&gt;
&lt;li&gt;Updating state is very fast.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now let's get to the practical understanding of the topic at hand.&lt;/p&gt;

&lt;h2&gt;
  
  
  Importing useState
&lt;/h2&gt;

&lt;p&gt;To use useState, you have to import it into the component where you will be declaring it, or you can use React.useState to declare your variable. In this class, we will be importing it as it's most likely the method you will see being used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from 'react'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;useState is a named export destructured from the React library, hence why it's wrapped in curly braces. When we move on to other hooks, they will be wrapped similarly in curly braces.&lt;/p&gt;

&lt;h2&gt;
  
  
  Declaring a useState variable
&lt;/h2&gt;

&lt;p&gt;useState has two variables: the initialValue and the updating function. These variables are destructured in an array, with the first variable being assigned the value in the useState function, while the second variable is the function that updates the state. I will make this explanation clearer in the example below.&lt;/p&gt;

&lt;p&gt;To declare a useState hook, you run the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, setState] = useState(initialValue)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are not obliged to name your variables state and setState. You can name them anything. It could be oranges and setOranges. Just make sure to follow the naming convention by letting your second variable start with set.&lt;/p&gt;

&lt;p&gt;You are allowed to have as many states as possible in a component. For instance, if you have a form component where you have to take the name, address and age of the user, you can simply do it like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from 'react'

const userForm = () =&amp;gt; {

    const [name, setName] = useState("John")
    const [address, setAddress] = useState("14, mayne street, Indiana")
    const [age, setAge] = useState(28)

  return (
      &amp;lt;div&amp;gt;
          &amp;lt;input type='text' value={console.log(name)}/&amp;gt;
          &amp;lt;input type='text' value={console.log(address)}/&amp;gt;
          &amp;lt;input type='number' value={console.log(age)}/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default userForm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the code above, you will understand better what I mean when I say the first variable is assigned the initialValue set in the useState function.&lt;/p&gt;

&lt;p&gt;Let's check the console to see its output.&lt;/p&gt;

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

&lt;p&gt;With the above result, I want to be sure you have an inkling of an idea of the value the first variable is assigned to. If the useState("John") function for the name was an empty string like this useState(" "), that will be the initialValue of name. The same applies to the rest of the state values.&lt;/p&gt;

&lt;h2&gt;
  
  
  Updating a useState variable
&lt;/h2&gt;

&lt;p&gt;To update the value of the above example, we will be using the second variable, which is the function updater. There will be some addition to the code, as we will be using events to update the function. Well, as you know, events are the actions that place to make a static website an interactive one.&lt;/p&gt;

&lt;p&gt;Now let's get to it. We will be using the same code as above, but with some changes.import React, {useState} from 'react'&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from 'react'

const userForm = () =&amp;gt; {

    const [name, setName] = useState("John")
    const [address, setAddress] = useState("14, mayne street, Indiana")
    const [age, setAge] = useState(28)

  return (
      &amp;lt;div&amp;gt;
          &amp;lt;input type='text'
              value={console.log(name)}
              onChange={ ((event)=&amp;gt; setName(event.target.value))} /&amp;gt;
          &amp;lt;input type='text'
              value={console.log(address)}
              onChange={ ((event)=&amp;gt; setAddress(event.target.value))}/&amp;gt;
          &amp;lt;input type='number'
              value={console.log(age)}
              onChange={ ((event)=&amp;gt; setAge(event.target.value))}/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default userForm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the code, we can see the onChange event being called. And inside the onChange event, we are using the second variable for each state to update the state from the initialValue.&lt;/p&gt;

&lt;p&gt;To update the state with the onChange event, we have to use a prop which could be named event as in our case, or e or ev as some people do. It's just to note that an event is taking place in the function. After all of this is done, you can type in your input box and watch the state update. Take a look at my input box and the console below.&lt;/p&gt;

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

&lt;p&gt;And in the console, it has been updated to this value in my input box. You can try it too, with a different input.&lt;/p&gt;

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

&lt;p&gt;From the example above, we used string and number as our data types. You can use other data types as well and not just these. I'll declare some new states with other data types so you don't get confused about what they may look like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from 'react'

const userForm = () =&amp;gt; {

    const [name, setName] = useState("John")
    const [address, setAddress] = useState(null)
    const [age, setAge] = useState(28)
    const [scores, setScores] = useState({ 'English': 75, 'Science': 64 })
    const [favoriteFood, setFavoriteFood] = useState(['rice', 'beans', 'cereal'])

  return (
      &amp;lt;div&amp;gt;
          &amp;lt;input type='text' value={console.log(name)}/&amp;gt;
          &amp;lt;input type='text' value={console.log(address)}/&amp;gt;
          &amp;lt;input type='number' value={console.log(age)}/&amp;gt;
          &amp;lt;input type='number' value={console.log(scores)}/&amp;gt;
          &amp;lt;input type='number' value={console.log(favoriteFood)}/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default userForm
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's look in the console to see our output as we have used different other data types.&lt;/p&gt;

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

&lt;p&gt;There isn't much difference in updating these other data types. The processes are the same. Just create an input element in your JSX for them and update them accordingly.&lt;/p&gt;

&lt;p&gt;In the next article, we will be learning &lt;strong&gt;&lt;em&gt;useEffect&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Hope this was helpful. If you have any questions, please feel free to ask me anytime. Also, don’t forget to follow me and like this tutorial.&lt;/p&gt;

&lt;p&gt;Thanks and have a great day.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React Series: Introduction</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Sat, 25 Mar 2023 16:57:12 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/react-series-introduction-55dj</link>
      <guid>https://forem.com/oluwatrillions/react-series-introduction-55dj</guid>
      <description>&lt;h2&gt;
  
  
  Topics
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;br&gt;
Why Use React&lt;br&gt;
What are Components&lt;br&gt;
What is JSX&lt;br&gt;
Props&lt;br&gt;
State.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is going to be a React series discussing React and Hooks. We will discuss an overview of React in today's topic and then proceed to discuss Hooks from the next article. It's going to be a hands-on series where you will learn so much as a beginner, and then proceed on to intermediate and advanced levels in React. Let's get started.&lt;/p&gt;
&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;p&gt;React is an open-source JavaScript library for building dynamic and interactive user interfaces both on the web and on mobile. It is widely popular and has about the largest community of developers using it. As opposed to the mix-up of React being a framework, it is a library.&lt;/p&gt;

&lt;p&gt;Everything in React is built inside a component. Components house every UI and functionality in a React app. The components serve as several building blocks that are put together to build a house. We will discuss components in the later part of this article.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why Use React:
&lt;/h2&gt;

&lt;p&gt;React is very easy to learn and understand. As a lot of developers say, learning React makes JavaScript a lot easier.&lt;/p&gt;

&lt;p&gt;React is a component-based library that helps you divide your code into small, reusable, organized and modular components. Because a React program is a tree with the main component being the &lt;strong&gt;&lt;em&gt;App&lt;/em&gt;&lt;/strong&gt;, the small, reusable components are its branches.&lt;/p&gt;

&lt;p&gt;React maintains a Virtual DOM, which makes it very fast. A Virtual DOM is a representation of the real DOM. So with React, when changes are made in an app, the Virtual DOM only updates the node where the changes were made in the real DOM. So unlike JavaScript where the whole page reloads when changes are made, React only updates the component where the changes were made.&lt;/p&gt;

&lt;p&gt;It is perfect for building interactive and reusable user interfaces.&lt;/p&gt;

&lt;p&gt;It makes debugging easy. Since React apps flow like rainfall (from top to bottom), it makes debugging from one line of code to the next easier and less confusing.&lt;/p&gt;

&lt;p&gt;It is efficient in building small to large applications.&lt;/p&gt;

&lt;p&gt;It is suitable for building mobile and web applications.&lt;/p&gt;
&lt;h2&gt;
  
  
  What are Components?
&lt;/h2&gt;

&lt;p&gt;A car consists of several parts like the brake, steering, engine, carburetor, battery etc. Except these parts are wired and screwed together, the car is not driveable; it is just a piece of parts. Once these parts are screwed and wired together, the car comes to life. The same thing applies to a React app. It consists of several building blocks called components. The component houses every function, method and property that belongs to a particular user interface.&lt;/p&gt;

&lt;p&gt;These individual components are then wired together under the parent UI usually called the &lt;strong&gt;&lt;em&gt;App&lt;/em&gt;&lt;/strong&gt;. The &lt;em&gt;App&lt;/em&gt; in return becomes the face of the entire React app. It represents the totality of the project, housing several individual components.&lt;/p&gt;

&lt;p&gt;In React, there are two (2) types of components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Functional components&lt;/li&gt;
&lt;li&gt;Class functions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Functional Components&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;This is the most popular type of component you will see in React apps these days. It's not so different from JavaScript functions. Data may or may not be passed as parameters to these functions, but data can be passed from one component to the other through props. Let's see an example of a Functional component.&lt;br&gt;
&lt;/p&gt;

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

const Test = () =&amp;gt; {
  return (
      &amp;lt;div&amp;gt;
          &amp;lt;h1&amp;gt;This is a Functional component&amp;lt;/h1&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

export default Test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Class Components&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;A class component is in truth more robust than a functional component, but you will hardly see developers use it these days. Not because it is out of vogue, but because it is more complicated to understand. It is not beginner friendly. A class component comes with a render method that renders onto the screen. Below is an example of the class component.&lt;br&gt;
&lt;/p&gt;

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

export default class Test extends React.Component {
  render() {
    return (
      &amp;lt;div&amp;gt;This is a class component&amp;lt;/div&amp;gt;
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: Throughout this series, we will be using the Functional component for our examples.&lt;/p&gt;

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

&lt;p&gt;Its full meaning is JavaScript XML, and it is a JavaScript syntax that allows you to write HTML directly in your React. It helps to describe how the user interface will appear in the React library.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Test = () =&amp;gt; {
  return (
/*
      &amp;lt;div&amp;gt;
          &amp;lt;h1&amp;gt;This is a Functional component&amp;lt;/h1&amp;gt;
    &amp;lt;/div&amp;gt;
*/ This here is an example of JSX. This is HTML in JavaScript.
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Props:
&lt;/h2&gt;

&lt;p&gt;Props are used to pass data from one component to the other. Props are passed down, not the other way. What that means is, props are passed from parent to sibling components and not the other way.&lt;/p&gt;

&lt;p&gt;To have a better understanding of props, you can check out &lt;a href="https://medium.com/@oluwatrillions/props-what-you-need-to-know-242152b4db62" rel="noopener noreferrer"&gt;Props: What you need to know&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  State:
&lt;/h2&gt;

&lt;p&gt;This is the present value of an object whose value may change over time as a result of an event in the application. The event can be a result of a click of a button, an onChange event etc. The most prominent way to handle state in React is the useState Hook. We will be moving on to Hooks, and useState will be the first Hook we discuss in the next article. &lt;/p&gt;

&lt;p&gt;Hope this was helpful. If you have any questions, please feel free to ask me anytime. Also, don’t forget to follow me and like this tutorial.&lt;/p&gt;

&lt;p&gt;Thanks and have a great weekend.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>HTTP request: Fetch vs Axios</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Wed, 22 Mar 2023 13:08:33 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/http-request-fetch-vs-axios-591f</link>
      <guid>https://forem.com/oluwatrillions/http-request-fetch-vs-axios-591f</guid>
      <description>&lt;p&gt;The bedrock of any programming language is the ability to make requests from an API. The absence of this means we are operating a static non-dynamic application. Data fetching is key in software development, as the majority of the data we would be needing to operate with comes from an API. Using JavaScript means we are building a dynamic web application that fetches data from an API and also sends the same, hence, we will be using some methods to fetch these data from its source, receive these data and also send some information to an API where they will be processed and used. This calls for the use of data-fetching methods.&lt;/p&gt;

&lt;p&gt;In JavaScript, there are several methods and ways through which you can make your HTTP requests, but we will be talking about the two most used HTTP clients;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Fetch&lt;/li&gt;
&lt;li&gt;Axios&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These two HTTP clients are used to build CRUD (Create, Read, Update, Delete) operations. A CRUD operation is used to perform certain requests and calls from and to an API. There are mainly four HTTP request methods that can be performed using either Fetch or Axios:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GET&lt;/strong&gt;: Used to request data from a resource.&lt;br&gt;
&lt;strong&gt;POST&lt;/strong&gt;: Used to send data to a resource.&lt;br&gt;
&lt;strong&gt;PUT&lt;/strong&gt;: Used to update data in a resource.&lt;br&gt;
&lt;strong&gt;DELETE&lt;/strong&gt;: Used to delete data in a resource.&lt;/p&gt;

&lt;p&gt;Both of these methods have some differences and similarities, and I am sure as we take a deeper dive in each one, we will discover them. Hang on with me as we explore them together.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;FETCH&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Fetch is a method that stemmed out of the Fetch API interface. The Fetch API is a native JavaScript API and it is available in all modern browsers. Since it is an in-built JavaScript API, you do not to install it.&lt;/p&gt;

&lt;p&gt;Fetch returns a Promise. A promise is used to handle asynchronous operations in JavaScript. It holds the result of the operation in 3 stages; pending, fulfilled or rejected.&lt;/p&gt;

&lt;p&gt;Now back to Fetch, let’s see in practical terms how Fetch is used.&lt;/p&gt;

&lt;p&gt;Fetch can be used for data fetching in 2 ways;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;USING FETCH WITHOUT CONFIGURATION SETTINGS:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When using fetch without configuration settings, the default method for Fetch is a GET. That means you are trying to pull data from a resource.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://jsonplaceholder.typicode.com/users')
    .then((response) =&amp;gt; response.json())
    .then((data) =&amp;gt; {
        console.log(data);
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result of our fetch is thus:&lt;/p&gt;

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

&lt;p&gt;Using this method, Fetch knows you are performing a GET operation, so you don’t necessarily need to do this &lt;code&gt;fetch.get('https://jsonplaceholder.typicode.com/users')&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;USING FETCH WITH CONFIGURATION SETTINGS:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When setting configurations with Fetch, a lot of parameters can be set manually, such as method, headers, data etc. This method is more suitable if you need to stringify the data, if you are expecting a different content-type, if you need to set a timeout for the page etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const newUser = {
    name: 'Michael Toby',
    address: 'Lagos, Nigeria',
    job: 'Web Developer'
}

fetch('https://jsonplaceholder.typicode.com/users', {
    method: 'POST',
    headers: {
        "content-type": "application/json"
    },
    body: JSON.stringify(newUser)
})
    .then((response) =&amp;gt; response.json())
    .then((data) =&amp;gt; {
        console.log(data);
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code above is a POST method, meaning we are sending data to an API. The data we are sending is the newUser object, and if you see the id in the response below, you will see the id has been updated to 11.&lt;/p&gt;

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

&lt;p&gt;.then() is where the promise is handled. It either resolves or rejects the response from the API. When it resolves, we then convert our response to json(), after which we use another .then() to receive the data we are expecting.&lt;/p&gt;

&lt;p&gt;To handle error in fetch, you use the &lt;strong&gt;.catch()&lt;/strong&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://jsonplaceholder.typicode.com/users', )
    .then((response) =&amp;gt; response.json())
    .then((data) =&amp;gt; {
        console.log(data);
    })
    .catch((error) =&amp;gt; {
        console.log(error.message)
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And if you want to create a custom error message, you can do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://jsonplaceholder.typicode.com/users', )
    .then((response) =&amp;gt; {
        if (!response.ok) {
            throw new Error(
                `This is a ${response.status} error`
            )
        }
        return response.json()
    })
    .catch((error) =&amp;gt; {
        console.log(error.message);
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;POINTS TO NOTE&lt;/strong&gt;:&lt;br&gt;
The object you are expecting from the API is in the response object.&lt;br&gt;
Fetch does not convert its data to json by default.&lt;br&gt;
When sending or updating data to an API, your content will always be in the body property. Also, always remember to JSON.stringify() your content.&lt;br&gt;
Always set content-type to application/json or your preferred type.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AXIOS&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Axios is a third party library that allows you to make HTTP requests. And just like Fetch, it returns a promise.&lt;/p&gt;

&lt;p&gt;To install axios, you can run this code as it pertains to you.&lt;/p&gt;

&lt;p&gt;Install using npm&lt;br&gt;
&lt;code&gt;npm install axios&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Install using yarn&lt;br&gt;
&lt;code&gt;yarn add axios&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Like Fetch, Axios can be used for data fetching in 2 ways;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;USING AXIOS WITHOUT CONFIGURATION SETTINGS:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Using axios without configurations is a default GET method. And that is used when we are trying to fetch data from the resouce. Let’s get at it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;axios('https://jsonplaceholder.typicode.com/users')
    .then((response) =&amp;gt; {
    console.log(response.data);
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result will be the same as Fetch, only difference is that the result will be found in an array inside the data file.&lt;/p&gt;

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

&lt;ol&gt;
&lt;li&gt;USING AXIOS WITH CONFIGURATION SETTINGS:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Using axios with configuration parameter isn’t much different from Fetch. The two obvious difference being that content is attached to data, as against body in Fetch, and you don’t need to stringify the content as axios automatically converts it’s data into json(). Let’s see for ourselves.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const newUser = {
    name: 'Michael Toby',
    address: 'Lagos, Nigeria',
    job: 'Web Developer'
}

axios('https://jsonplaceholder.typicode.com/users', {
    method: 'POST',
    headers: {
        "content-type": "application/json"
    },
    data: newUser
})
    .then((response) =&amp;gt; {
        console.log(response.data);
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not an array because it is a single object. Moreso, the result is the same as the Fetch Method.&lt;/p&gt;

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

&lt;p&gt;We can also write the code like this and get the same result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const newUser = {
    name: 'Michael Toby',
    address: 'Lagos, Nigeria',
    job: 'Web Developer'
}

axios({
    url: 'https://jsonplaceholder.typicode.com/users' 
    method: 'POST',
    headers: {
        "content-type": "application/json"
    },
    data: newUser
})
    .then((response) =&amp;gt; {
        console.log(response.data);
    })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Like Fetch, &lt;strong&gt;.then()&lt;/strong&gt; is where the promise in axios is handled. It either resolves or rejects the response from the API.&lt;/p&gt;

&lt;p&gt;To handle error in axios, you use the &lt;strong&gt;.catch()&lt;/strong&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;axios('https://jsonplaceholder.typicode.com/users')
    .then((response) =&amp;gt; console.log(response.data))
        .catch((error)=&amp;gt;{
        if (error.response) {
        // When a request is made but the resource returns an error
        console.log(error.response.data);
        console.log(error.response.status);
    } else if (error.request) {
        // When the request is made but no response from the resource.
        console.log(error.request);
    } else {
        console.log('Error', error.message);
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;POINTS TO NOTE&lt;/strong&gt;:&lt;br&gt;
The object you are expecting from the API is in the data object.&lt;br&gt;
Data is automatically set to the json format by default.&lt;br&gt;
When sending or updating data to an API, your content will always be in the data property. Also, no need to stringify your content.&lt;/p&gt;

&lt;p&gt;Hope this was helpful. If you have any questions, please feel free to ask me anytime. Also, don’t forget to follow me and like this tutorial.&lt;/p&gt;

&lt;p&gt;Thanks and have a great day.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>var, let and const.</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Sat, 18 Mar 2023 16:09:28 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/var-let-and-const-27nj</link>
      <guid>https://forem.com/oluwatrillions/var-let-and-const-27nj</guid>
      <description>&lt;p&gt;There were quite some feature changes in JavaScript ES6, and notable among them is the variable declaration keyword. These keywords have been game-changers in understanding the scope and concepts of declared variables. The &lt;strong&gt;var&lt;/strong&gt; keyword is the oldest among the 3 and has been used for several years, but until recently when updates were made to the ES6, the scope problem was solved by the introduction of new keywords: &lt;strong&gt;let&lt;/strong&gt; and &lt;strong&gt;const&lt;/strong&gt;. Today, we will be discussing all three (3) keywords, their scope and concepts, and when to use them, but first, we will need to talk about &lt;strong&gt;scope&lt;/strong&gt; so it helps us understand these keywords when mentioned.&lt;/p&gt;

&lt;p&gt;When we talk about &lt;strong&gt;SCOPE&lt;/strong&gt;, we talk about the accessibility of a variable. A variable can either be scoped &lt;strong&gt;globally&lt;/strong&gt; or &lt;strong&gt;locally&lt;/strong&gt;. A &lt;strong&gt;global&lt;/strong&gt; variable is one that is declared outside a function, so it can be accessed anywhere in the code, while &lt;strong&gt;local&lt;/strong&gt; variables are declared inside a function and can only be accessed within the function where it was created. Now that &lt;strong&gt;scope&lt;/strong&gt; has been understood, let’s move on to the main topic of the day.&lt;/p&gt;

&lt;p&gt;*** &lt;strong&gt;&lt;em&gt;VAR&lt;/em&gt;&lt;/strong&gt; ***&lt;br&gt;
This has been the oldest declarative keyword in JavaScript. A lot of early JavaScript adopters are so used to it I bet it will be difficult to take it away from their heads, so don’t expect to only encounter &lt;strong&gt;var&lt;/strong&gt; in legacy codebases or if you’re working with super senior developers. The &lt;strong&gt;var&lt;/strong&gt; keyword has its flaws hence the creation of the other two (2) keywords. Let’s play with some codes to see some of these flaws.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;SCOPING OF VAR&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Scoping of &lt;strong&gt;var&lt;/strong&gt; relates mainly to how the variable was declared and how it is being accessed. Var is &lt;strong&gt;function&lt;/strong&gt; scoped, so variables are not limited to being accessed in the block where they were declared. In the below code, we will see what it means to declare a &lt;strong&gt;var&lt;/strong&gt; variable globally and locally and the scope of each.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var games = 'football'

function football() {
    var striker = 'michael'
}
console.log(games);// football
console.log(striker);// Error: striker is not defined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of this code in the console will be:&lt;/p&gt;

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

&lt;p&gt;The output from the &lt;strong&gt;games&lt;/strong&gt; variable was &lt;strong&gt;football&lt;/strong&gt;, while &lt;strong&gt;striker&lt;/strong&gt; gave an error. The reason is that &lt;strong&gt;games&lt;/strong&gt; is a &lt;strong&gt;global&lt;/strong&gt; variable and so it can be accessed anywhere in the function, while &lt;strong&gt;striker&lt;/strong&gt; is a &lt;strong&gt;local&lt;/strong&gt; variable and can only be accessed anywhere inside the function.&lt;/p&gt;

&lt;p&gt;In the below code, we will try to access the &lt;strong&gt;games&lt;/strong&gt; variable inside the function. Let’s see the output.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var games = 'football'

function football() {
    var striker = 'michael'
    console.log(striker);
    console.log(games);
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Tadaaaa!!! Like magic, both variables output without errors. And that is because global variables will output anywhere they are called.&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;RE-DECLARATION OF VARIABLES&lt;/em&gt;&lt;/strong&gt;:&lt;br&gt;
A &lt;strong&gt;var&lt;/strong&gt; variable can be re-declared or updated. Let’s see that in code visuals.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function football() {
    var striker = 'michael'
    var striker = 'messi'
    striker = 'ronaldo'
    var striker = 'neymar'
    console.log(striker);
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;// The output of this code is neymmar&lt;/code&gt;&lt;br&gt;
From the above code, we declared the variable, re-declared it, updated it and then re-declared it again to arrive at &lt;em&gt;&lt;strong&gt;neymar&lt;/strong&gt;&lt;/em&gt; as our final output because that was our last declaration.&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;IMPORTANT&lt;/em&gt;&lt;/strong&gt;!!! This type of code above is the reason why &lt;strong&gt;var&lt;/strong&gt; is prone to causing errors. If you have forgotten you had an earlier variable named &lt;strong&gt;&lt;em&gt;striker&lt;/em&gt;&lt;/strong&gt; and it has been declared in some parts of the code with important values, and you mistakenly re-declare it, it could ruin the whole project you’re working on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;HOISTING WITH VAR&lt;/em&gt;&lt;/strong&gt;:&lt;br&gt;
JavaScript’s default behavior is moving all functions, classes and variables to the top of their scope before the execution of the code, so with var, variables are first initialized as &lt;strong&gt;&lt;em&gt;undefined&lt;/em&gt;&lt;/strong&gt; before the declaration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function football() {
console.log(striker);// undefined
    var striker = 'michael'
    console.log(striker);// michael
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;*** &lt;strong&gt;&lt;em&gt;LET&lt;/em&gt;&lt;/strong&gt; ***&lt;br&gt;
This is an improved keyword than &lt;strong&gt;&lt;em&gt;var&lt;/em&gt;&lt;/strong&gt;. &lt;strong&gt;&lt;em&gt;Let&lt;/em&gt;&lt;/strong&gt; us take a look at some of the improvements of the let keyword against the &lt;strong&gt;&lt;em&gt;var&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;BLOCK-SCOPED&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;It is &lt;em&gt;block-scoped&lt;/em&gt; and thereby variables declared inside the block can not be accessed outside it. Let’s take a peep at what that means.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function football() {
    let striker = 'michael'
if (striker.length = 6) {
        let forward = 'ronaldinho'
        console.log(forward);// line 7 ronaldinho
        }
    console.log(forward);// line 9 error
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of this code is:&lt;/p&gt;

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

&lt;p&gt;The output of the variable &lt;strong&gt;&lt;em&gt;forward&lt;/em&gt;&lt;/strong&gt; is &lt;em&gt;ronaldinho&lt;/em&gt;, because the variable was declared within the block of code, unlike in Line 9 which was called outside the block of code hence returning an error because the variable &lt;strong&gt;&lt;em&gt;forward&lt;/em&gt;&lt;/strong&gt; was not declared in the function named &lt;strong&gt;&lt;em&gt;football&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;RE-DECLARATION OF VARIABLES&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Variables declared with the keyword &lt;strong&gt;&lt;em&gt;let&lt;/em&gt;&lt;/strong&gt; cannot be re-declared as we saw with the &lt;strong&gt;&lt;em&gt;var&lt;/em&gt;&lt;/strong&gt; keyword. Let’s try an example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_function football() {
    let striker = 'michael'
    let striker = 'messi'
    console.log(striker);
}
football()_
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code will throw an error because &lt;strong&gt;striker&lt;/strong&gt; has been declared and so it can’t be re-declared. The output is this:&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;VARIABLES CAN BE UPDATED&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Variables can be updated after they have been declared.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function football() {
let forward = 'rooney'
    forward = 'mbappe'
    forward = 'kane'
    forward = 'salah'
    console.log(forward);
}
football()
// salah
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of our update variable is thus:&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;GLOBAL VARIABLES CAN BE ACCESSED IN THE BLOCK&lt;/em&gt;&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var games = 'football'
function football() {
    var striker = 'michael'
    console.log(striker);
    console.log(games);
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output will be the same as that of var.&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;HOISTING WITH LET&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Like &lt;strong&gt;var&lt;/strong&gt;, declarations, classes and functions are hoisted to the top of the code, but with &lt;strong&gt;let&lt;/strong&gt;, variables do not initialize as &lt;strong&gt;undefined&lt;/strong&gt;. &lt;em&gt;Let&lt;/em&gt; does not allow a variable to be called before it is declared. Let’s see how it plays out.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function football() {
console.log(striker);
    let striker = 'michael'
    console.log(striker);
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of this will be an error.&lt;/p&gt;

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

&lt;p&gt;*** &lt;strong&gt;&lt;em&gt;CONST&lt;/em&gt;&lt;/strong&gt; ***&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;const&lt;/em&gt;&lt;/strong&gt; variables are constants and their values can not be changed. &lt;em&gt;const&lt;/em&gt; shares the same similarities with &lt;strong&gt;let&lt;/strong&gt; with maybe very few differences. In addition to all the characteristics of &lt;strong&gt;let&lt;/strong&gt;, we can add these few other updates to const.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;ITS VALUES ARE CONSTANTS AND CANNOT BE UPDATED&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Any variable declared with the keyword &lt;strong&gt;&lt;em&gt;const&lt;/em&gt;&lt;/strong&gt;, can not be changed or updated. Unlike &lt;strong&gt;&lt;em&gt;var&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;let&lt;/em&gt;&lt;/strong&gt; where their values can be re-declared or updated, &lt;strong&gt;&lt;em&gt;const&lt;/em&gt;&lt;/strong&gt; doesn’t allow for that. Let’s see if we can try that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function football() {
const forward = 'rooney'
    forward = 'mbappe'
    console.log(forward);
}
football()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Well, this code threw an error. Let me share it so you can see it too.&lt;/p&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;THE PROPERTIES OF AN OBJECT CAN BE MANIPULATED&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;const&lt;/em&gt;&lt;/strong&gt; variables are constants and therefore they can not be changed. With objects, the properties can be manipulated but not directly. Let’s see how that can be done.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const shopping = {
    grocery: 'sausage',
    fruit: 'apple',
    vegetable: 'carrot'
}

shopping = {
    grocery: 'beef'
}
console.log(shopping.grocery);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we are trying to change the value of grocery. Can that be done? Well, let’s give it a try. Follow me.&lt;/p&gt;

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

&lt;p&gt;Oops…It threw us an &lt;strong&gt;error&lt;/strong&gt;. Well, that is expected because that isn’t the right way to change the value of the grocery property. Now, let’s do it the right way. To change the value of grocery, we will do it this way.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const shopping = {
    grocery: 'sausage',
    fruit: 'apple',
    vegetable: 'carrot'
}

shopping.grocery = 'beef'
console.log(shopping.grocery);// beef
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;HOISTING WITH CONST&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Just like &lt;em&gt;let&lt;/em&gt;, declarations are moved to the top of the code, but they are not initialized as &lt;em&gt;undefined&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Thanks for taking the time to go this far in the tutorial. If you have any questions, please feel free to ask me anytime. Also, don’t forget to follow me and like this tutorial.&lt;/p&gt;

&lt;p&gt;Thanks and have a great weekend.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>react</category>
    </item>
    <item>
      <title>Commonly Used String Methods</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Wed, 15 Mar 2023 17:00:45 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/commonly-used-string-methods-jod</link>
      <guid>https://forem.com/oluwatrillions/commonly-used-string-methods-jod</guid>
      <description>&lt;p&gt;A String is a data type that is synonymous with all programming languages, and that is because it is the most frequently used data type. In JavaScript, String is used to holding text, and in most cases, these texts are variables. Strings are used to convey messages, store values in the form of variables and manipulate and modify them. A &lt;strong&gt;string&lt;/strong&gt; is any variable whose value is stored in-between quotes (“ “). Strings can also represent non-text characters that are treated as texts e.g phone numbers in a form. A phone number can be represented by a string because they are not used in arithmetic calculations and most cases, they are usually preceded by a “+” sign, unlike what you will consider an &lt;strong&gt;integer&lt;/strong&gt; which can perform mathematical operations.&lt;/p&gt;

&lt;p&gt;Let’s highlight some of the important characteristics of a string data type:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Their values are stored in quotes (“ “).&lt;/li&gt;
&lt;li&gt;They can be used to store phone numbers.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You cannot mutate a string.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Length()&lt;/strong&gt;: The length property is used to calculate the length of the string. Let’s see how to apply the length property.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael'
const lengthofString = myString.length;
console.log('The length of the string is', lengthofString);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the console, the output will be: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;The length of the string is 18.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;There are 15 characters and 3 white spaces. White spaces will be counted alongside characters.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Concat()&lt;/strong&gt;: This method is used to add two or more string variables together. The strings can be combined using the &lt;strong&gt;concatenation&lt;/strong&gt; symbol (+).
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael '
const secondString = 'and I like to code';
const stringConcat = myString + '' + secondString
console.log(stringConcat);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method can also be done using the string &lt;strong&gt;concat&lt;/strong&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael '
const secondString = 'and I like to code';
const stringConcat = myString.concat(secondString)
console.log(stringConcat);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For both methods that were used, the output will be the same. In your console, the result will be:&lt;br&gt;
&lt;code&gt;My name is Michael and I like to code&lt;/code&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;CharAt()&lt;/strong&gt;: This method returns the value or character at the specified index of the string. The &lt;strong&gt;charAt&lt;/strong&gt; method is zero index based, so it starts counting from position 0.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael'   
const charOfString = myString.charAt(11);   
console.log(charOfString); // M
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;code&gt;The character at the index of 11 is M.&lt;/code&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;IndexOf()&lt;/strong&gt;: This method returns the index position of the given string. If the given string does not exist, it will return &lt;strong&gt;-1&lt;/strong&gt;. Let’s try to play around with both cases and see its return.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael'
const indexOfString = myString.indexOf('eis');
console.log(indexOfString);// The output is -1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The output of this case is -1 because our given string (‘eis’) does not exist in the string. Now let’s try the availability of the given string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael'
const indexOfString = myString.indexOf('is');
console.log(indexOfString);// The return in the console is 8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The return in the console is 8 because our given string (‘is’) exists and the first index of the string is 8.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;LastIndexOf()&lt;/strong&gt;: This method works just like the &lt;strong&gt;indexOf&lt;/strong&gt; only that it returns the last index of the given string. Let’s see how it works.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'My name is Michael and the color of my car is green'
const indexOfString = myString.lastIndexOf('is');
console.log(indexOfString);// 43
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the string above, our given string (‘is’) appeared twice in the sentence, so the &lt;strong&gt;lastIndexOf&lt;/strong&gt; method picked the index of its last occurrence which is 43.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;ToLowerCase()&lt;/strong&gt;: This method converts the string to lowercase. It removes every capitalization in the string.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I LOVE JAVASCRIPT AND REACT'
const stringMethod = myString.toLowerCase();
console.log(stringMethod);// i love javascript and react
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;ToUpperCase()&lt;/strong&gt;: It works as the opposite of the &lt;strong&gt;toLowerCase&lt;/strong&gt; method. This method capitalizes all the characters in the string.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'
const stringMethod = myString.toUpperCase();
console.log(stringMethod);// I LOVE JAVASCRIPT AND REACT
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Trim()&lt;/strong&gt;: This method is used to remove all the white spaces in the string.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = ' I love javascript and react '
console.log(myString.length);

const stringMethod = myString.trim();
console.log(stringMethod);
console.log(stringMethod.length);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result of the above code is:&lt;/p&gt;

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

&lt;p&gt;If you take note, &lt;strong&gt;myString&lt;/strong&gt; has a white space before the first text and another white space after the last text, so when we console.log the length, it returned &lt;strong&gt;29&lt;/strong&gt;. Then we used the &lt;strong&gt;trim()&lt;/strong&gt; method, and the white spaces were removed thereby returning &lt;strong&gt;27&lt;/strong&gt; after we checked the length.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Includes()&lt;/strong&gt;: This is one very useful string method. It comes in handy when searching through a large list, and maybe sifting data from an API. It is used to check if a string passes an argument. It returns a boolean and it is case-sensitive.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = ' I love javascript and react '
const stringMethod = myString.includes("java");
console.log(stringMethod);// true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the code above, we checked if our string includes java, and Yes it does, from the javascript word, that was why it returned &lt;strong&gt;true&lt;/strong&gt;.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;StartsWith()&lt;/strong&gt;: This is used when trying to check if a string &lt;strong&gt;starts with&lt;/strong&gt; a given string or character. It returns a boolean too like the &lt;strong&gt;includes&lt;/strong&gt; and it is case-sensitive.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'  
const stringMethod = myString.startsWith("I");  
console.log(stringMethod);// true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'  
const stringMethod = myString.startsWith("i");  
console.log(stringMethod);// false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;EndsWith()&lt;/strong&gt;: Just like the &lt;strong&gt;startsWith&lt;/strong&gt;, it checks if a string ends with a given string or character. It is case-sensitive and it returns a &lt;strong&gt;boolean&lt;/strong&gt;.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'
const stringMethod = myString.endsWith("act");
console.log(stringMethod);// true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'
const stringMethod = myString.endsWith("treat");
console.log(stringMethod);// false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Replace():&lt;/strong&gt; This method searches through the string, finds the first occurrence of a string and replaces it with the second argument. It receives two (2) parameters, the first being the one to be replaced, and the second the one to be replaced with. Let’s see it in action.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'
const stringMethod = myString.replace("react", "python");
console.log(stringMethod);// I love javascript and python
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Slice()&lt;/strong&gt;: It returns a part of a string as set in the parameter. The parameter sets the start and the end of the string.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myString = 'I love javascript and react'
const stringMethod = myString.slice(7, 17);
console.log(stringMethod);// javascript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are a couple of other string methods that are important to know, even though you may not get to use them everyday.&lt;/p&gt;

&lt;p&gt;I hope this tutorial has been helpful. If Yes, you can like and follow me.&lt;/p&gt;

&lt;p&gt;Thanks and have a great day.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Important Vscode Extensions In 2023</title>
      <dc:creator>Toby</dc:creator>
      <pubDate>Sat, 11 Mar 2023 12:59:17 +0000</pubDate>
      <link>https://forem.com/oluwatrillions/important-vscode-extensions-in-2023-265c</link>
      <guid>https://forem.com/oluwatrillions/important-vscode-extensions-in-2023-265c</guid>
      <description>&lt;p&gt;It's 2023, and Visual Studio Code is still the best Integrated Development Environment (IDE) out there. Vscode is the most popular IDE at the moment, not just because it's a Microsoft-licensed distribution of code, but also because it has an open-source community that contributes to the performance of the software. Amongst its so many features, the one that stands out for me is its integration with Git. Being able to push code to your GitHub from Vscode is the first of its kind and one that endears a lot of developers to the software.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;WHY USE VS CODE&lt;/strong&gt;:&lt;br&gt;
Vscode offers a lot of features that every developer needs and these features as we know were made to increase productivity. So in a nutshell, &lt;strong&gt;&lt;em&gt;Vscode enhances productivity&lt;/em&gt;&lt;/strong&gt;. These features help make coding easier, less time-consuming and improve productivity. Features range from debugging, code completion, code refactoring, and code snippets, to embedding Git. This is a lot of satisfaction. So my friends, let's get to the topic of this article, &lt;strong&gt;&lt;em&gt;the best vscode extensions in 2023&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I will be talking about the best vscode extensions that every developer needs in 2023, to help make coding interesting and at the same time help us achieve more. I'll break these extensions down into categories and list some of the extensions for each category. Let's get into it friends.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;LOCAL ENVIRONMENT&lt;/em&gt;&lt;/strong&gt;:&lt;br&gt;
If you need a local environment to help you see the changes that have been made in your code, these extensions are the best you should have a look at.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;LIVE SERVER&lt;/em&gt;&lt;/strong&gt;: Live server creates a local server environment for you which can be watched in your localhost:3000. This helps you see the real-time changes made in your code. This is very helpful when you want to watch what you are developing and want to be sure your code manifests the output. You should try it out today.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;CODE FORMATTING&lt;/em&gt;&lt;/strong&gt;:&lt;br&gt;
When you consistently write code in a style, it helps make your code readable, finely formatted and easier to work with and understood. But we all know writing code is a heck of a work, talk more keeping consistency when writing them. That is when code formatting extensions come into play. They help us format our unformatted codes and save us time having to go back to format them. These 2 extensions help in this category.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;PRETTIER&lt;/em&gt;&lt;/strong&gt;: This is an open-source opinionated code formatter that helps you format your code and make it look neat and pretty. It enforces its format style over your original code (once it is saved) and makes it clear and readable. You can also set your custom format style in the settings.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;BEAUTIFY&lt;/em&gt;&lt;/strong&gt;: If your code is written in JavaScript, CSS or HTML, then this extension is also a good fit for code formatting. You can set how you want your code to be formatted in the settings, and that will be used as the default settings for your code formatting.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;CODE SNIPPETS&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Code Snippets are small reusable code blocks that are added to code files as templates. They help developers maximize their time by using the templates instead of having to write the code for the files from scratch. Let's look at a couple of them below.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;JAVASCRIPT(ES6) CODE SNIPPETS&lt;/em&gt;&lt;/strong&gt;: As we all know, JavaScript is the most popular programming language in the world, and it is only right to have a code snippet for JavaScript-related codes. This code snippet is one of the most used at the moment and it has been very helpful to a lot of developers. It saves the time to write boilerplate codes and just advances you to writing the logic to your code.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;SNIPPET&lt;/em&gt;&lt;/strong&gt;: This is one of the best code snippet extensions. It is laced with AI to automatically detect the programming language in the current editor window. It is a collection of extensions for the most commonly used programming languages and it helps improve productivity. It saves you the time of having to install several language extensions.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;p&gt;&lt;strong&gt;&lt;em&gt;INTELLIGENT CODE COMPLETION&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Code Autocomplete extensions help suggest your next line of code through the use of Artificial Intelligence. They suggest completion codes by looking at the context of the earlier codes and suggest codes that will fit in in completion, even down to classes and variable names. Let's take a look at the most popular ones.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;GITHUB CO-PILOT&lt;/em&gt;&lt;/strong&gt;: This extension I would say set the precedence in code auto-completion. It is a cloud-based AI-powered extension that supports autocompletion in all programming languages and helps a lot in work productivity and time management. It is a brilliant innovation in this space.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg21icmkmfh5z65m7g3l1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg21icmkmfh5z65m7g3l1.png" alt="co-pilot" width="800" height="447"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;TABNINE&lt;/em&gt;&lt;/strong&gt;: This is another AI-powered autocompletion extension that works with all programming languages. It helps you to write your code and suggests auto-complete codes along with your coding context. It is a powerful tool that helps reduce the time spent writing code and improving productivity.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

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

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;INTELLICODE&lt;/em&gt;&lt;/strong&gt;: Most developers are familiar with intelliSense; the intelligent visual studio extension. IntelliCode is the Ai-integrated and enhanced intelliSense. It predicts the most likely code completion suggestion, and it can be used with all programming languages.&lt;/li&gt;
&lt;/ol&gt;

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

&lt;p&gt;These extensions will save you a whole lot of time while coding and also improve your productivity while at it.&lt;/p&gt;

&lt;p&gt;I hope this tutorial has been helpful. If Yes, you can like and follow me.&lt;/p&gt;

&lt;p&gt;Thanks and have a great weekend.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
