<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Boateng Dickson - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Boateng Dickson - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 22:37:23 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/dboatengx/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Redux and Redux Toolkit – Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ When I started learning Redux, I found it challenging to wrap my head around the concepts. Despite reading many online resources, I struggled to grasp the core ideas.  While the online tutorials and guides provided helpful information, I needed more ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/redux-and-redux-toolkit-for-beginners/</link>
                <guid isPermaLink="false">66bd90551bb54b9103c678bb</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Thu, 04 May 2023 14:20:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/redux-for-beginners1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I started learning Redux, I found it challenging to wrap my head around the concepts. Despite reading many online resources, I struggled to grasp the core ideas. </p>
<p>While the online tutorials and guides provided helpful information, I needed more clarity to really understand Redux.</p>
<p>But with persistence and practice, I eventually gained a better understanding of Redux's key concepts and successfully implemented them in my projects.</p>
<p>In this article, I will explain Redux in the simplest possible way. As someone who initially struggled with understanding Redux, I know how frustrating it can be to learn a new concept. But I hope this article will help make the concepts of Redux more accessible to beginner learners.</p>
<p>We will also delve into Redux Toolkit, a collection of tools that simplify using Redux. These tools help make Redux less daunting and easier to use.</p>
<h2 id="heading-what-is-redux">What is Redux?</h2>
<p>Redux is a state management library that allows you to manage the state of your JavaScript applications more efficiently and predictably.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-165.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Imagine you are building a house and need to keep track of all the materials you use and how much money you spend. Instead of keeping track of everything in your head or on a piece of paper, you could use a ledger to keep track of every transaction. Redux works similarly by keeping track of your application's state in a single place called the "store."</p>
<p>Let's say you're building an e-commerce site. You may need to keep track of the items in a user's cart, their payment information, and their shipping details. </p>
<p>Instead of passing this information from component to component using props, Redux allows you to store them in one central location where they can be easily accessed and updated. This makes it easier to manage complex states and keep your application organized.</p>
<p>It's important to note that Redux is not limited to React and you can use it with other frameworks or even vanilla JavaScript.</p>
<h2 id="heading-why-should-i-use-redux">Why Should I Use Redux?</h2>
<p>Redux can help simplify the state management process, especially when dealing with complex and interconnected components. Here are some reasons why you might want to use Redux in your application:</p>
<ol>
<li><strong>Centralized state management:</strong> With Redux, you can maintain the state of your entire application in a single store, making it easier to manage and access data across components.</li>
<li><strong>Predictable state updates:</strong> Redux has a clear flow of data, which means changes to the state can only happen when you create an action and send it through Redux. This makes it easy to understand how your application's data will change in response to user actions.</li>
<li><strong>Easier debugging:</strong> With Redux DevTools, you have a clear record of all the changes to your application's state. This makes locating and fixing issues in your code easier, saving you time and effort in the debugging process.</li>
<li><strong>Better performance:</strong> By minimizing the number of state updates and reducing the need for prop drilling, Redux helps improve your application's performance.</li>
</ol>
<h2 id="heading-how-does-redux-work">How Does Redux Work?</h2>
<p>As previously mentioned, Redux enables you to maintain a single centralized store that manages the state of your entire application. All components in your application can access this store and update or retrieve data from it as needed. </p>
<p>The key components that enable this centralized approach to state management are:</p>
<ol>
<li>Store</li>
<li>Actions</li>
<li>Dispatch</li>
<li>Reducers</li>
</ol>
<p>Let’s explore the role of each one:</p>
<h3 id="heading-the-store">The Store</h3>
<p>The Redux store is like a giant container that holds all the data for your application.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-167.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Think of the store as a box with different compartments for different data types. You can store any data you want in these compartments, and it can hold various kinds of data, such as strings, numbers, arrays, objects, and even functions.</p>
<p>Also, the store is the single source of truth for your application's state. This means that any component in your application can access it to retrieve and update data.</p>
<h3 id="heading-actions">Actions</h3>
<p>An action is an object that describes what changes need to be made to the state of your application. It sends data from your application to the Redux store and serves as the only way to update the store.</p>
<p>An action must have a "type" property describing the action being performed. This "type" property is typically defined as a string constant to ensure consistency and avoid typos.</p>
<p>In addition to the "type" property, an action can have a "payload" property. The "payload" property represents the data that provides additional information about the action being performed. For example, if an action type is <code>ADD_TASK</code>, the payload might be an object containing a new task item's "id", "text", and "completed status".</p>
<p>Here's an example of an action:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_TASK'</span>,
  <span class="hljs-attr">payload</span>: {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">text</span>: <span class="hljs-string">'Buy groceries'</span>,
    <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
  }
}
</code></pre>
<p>Note that to create actions, we use action creators. Action creators are functions that create and return action objects.</p>
<p>Here is an example of an action creator that takes in a task's text and returns an action object to add the task to the Redux store:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTask</span>(<span class="hljs-params">taskText</span>) </span>{
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_TASK'</span>,
    <span class="hljs-attr">payload</span>: {
      <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">text</span>: taskText,
      <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
    }
  }
}
</code></pre>
<p>An appropriate analogy for actions and action creators would be a chef using a recipe. The recipe outlines the required ingredients and instructions to prepare a dish, similar to how an action in Redux specifies the needed details to modify the state of an application. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-171.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this scenario, the chef represents the action creator, who follows the recipe to create the dish, similar to how an action creator creates an action based on predefined properties.</p>
<h3 id="heading-dispatch">Dispatch</h3>
<p>In Redux, dispatch is a function provided by the store that allows you to send an action to update the state of your application. When you call <code>dispatch</code>, the store runs an action through all of the available reducers, which in turn update the state accordingly.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-185.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can think of <code>dispatch</code> as a mail carrier who delivers mail to different departments in a large company. Just like how the mail carrier delivers mail to different departments, <code>dispatch</code> delivers actions to various reducers in your Redux store. Each reducer is like a department in the company that processes the mail and updates its own part of the company's data.</p>
<h3 id="heading-reducers">Reducers</h3>
<p>In Redux, a reducer is a function that takes in the current state of an application and an action as arguments, and returns a new state based on the action.</p>
<p>Here's an example of a simple reducer:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">count</span>: <span class="hljs-number">0</span>
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counterReducer</span>(<span class="hljs-params">state = initialState, action</span>) </span>{
  <span class="hljs-keyword">switch</span>(action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'INCREMENT'</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'DECREMENT'</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
}
</code></pre>
<p>In the above code, we have a simple reducer called "counterReducer" that manages the state of a count variable. It takes in two arguments: <code>state</code> and <code>action</code>. The <code>state</code> argument represents the current state of your application, while the <code>action</code> argument represents the action dispatched to modify the state.</p>
<p>The reducer then uses a switch statement to check the "type" of the action, and based on that type, it updates the state accordingly. </p>
<p>For example, if the action type is "INCREMENT", the reducer returns a new state object with the count incremented by 1. Also, if the action type is "DECREMENT", the reducer returns a new state object with the count decremented by 1.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-172.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A perfect analogy for a reducer would be a kitchen blender. Just like a blender takes in different ingredients, blends them, and produces a smooth mixture, a reducer takes in the current state of an application and an action, processes them together, and produces a new state.</p>
<h2 id="heading-example-project-real-app-implementation">Example Project – Real App Implementation</h2>
<p>Now that you understand the basics of Redux and how it works, let's create a simple real-world project. For this example, we'll create a basic ToDo List application where you can add and delete tasks.</p>
<h3 id="heading-step-1-how-to-set-up-the-project">Step 1: How to set up the project</h3>
<p>Create a new React project by running the following command in your terminal. Replace <em>"your-project-name"</em> with the name of your project.</p>
<pre><code>npm create vite@latest your-project-name -- --template react

cd your-project-name

npm install
</code></pre><p>The above command sequence will create a new React project using the Vite build tool and install all necessary dependencies.</p>
<h3 id="heading-step-2-how-to-install-redux">Step 2: How to install Redux</h3>
<p>Redux requires a few dependencies for its operations, namely:</p>
<ul>
<li><strong>Redux:</strong> The core library enables the redux architecture.</li>
<li><strong>React Redux:</strong> Simplifies connecting your React components to the Redux store.</li>
<li><strong>Redux Thunk:</strong> Allows you to write asynchronous logic in your Redux actions.</li>
<li><strong>Redux DevTools Extension:</strong> Connects your Redux application to Redux DevTools</li>
</ul>
<p>You can install them using npm, as shown below:</p>
<pre><code>npm install \

redux \

react-redux \

redux-thunk \

redux-devtools-extension
</code></pre><h3 id="heading-step-3-how-to-set-up-reducers">Step 3: How to set up reducers</h3>
<p>Now let's create the reducer for our application. </p>
<p>In the <code>src</code> directory, create a new folder called <code>reducers</code>, and inside that folder, create two new files: <code>index.js</code> and <code>taskReducer.js</code>.</p>
<p>The <code>index.js</code> file represents the root reducer, which combines all the individual reducers in the application. In contrast, the <code>taskReducer.js</code> file is one of the individual reducers that will be combined in the root reducer.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> taskReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"./taskReducer"</span>;
<span class="hljs-keyword">import</span> { combineReducers } <span class="hljs-keyword">from</span> <span class="hljs-string">"redux"</span>;

<span class="hljs-keyword">const</span> rootReducer = combineReducers({
  <span class="hljs-attr">tasks</span>: taskReducer,
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> rootReducer;
</code></pre>
<p>In the above <code>index.js</code> file, we use the <code>combineReducers</code> function to combine all the individual reducers into a single root reducer. In this case, we only have one reducer (<code>taskReducer</code>), so we pass it in as an argument to <code>combineReducers</code>.</p>
<p>The resulting combined reducer is then exported so that other files in the application can import and use it to create the store.</p>
<p>Here's the code for <code>taskReducer</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">tasks</span>: []
};

<span class="hljs-keyword">const</span> taskReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_TASK'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">tasks</span>: [...state.tasks, action.payload]
      };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'DELETE_TASK'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">tasks</span>: state.tasks.filter(<span class="hljs-function"><span class="hljs-params">task</span> =&gt;</span> task.id !== action.payload)
      };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> rootReducer;
</code></pre>
<p>Inside the above <code>taskReducer.js</code> file, we define a reducer function that takes two arguments: <code>state</code> and <code>action</code>. The <code>state</code> argument represents the current state of the application, while the <code>action</code> argument represents the action being dispatched to update the state.</p>
<p>The <code>switch</code> statement inside the reducer handles different cases based on the "type" of the action. For example, if the action type is <code>ADD_TASK</code>, the reducer returns a new state object with a new task added to the <code>tasks</code> array. And if the action type is <code>DELETE_TASK</code>, the reducer returns a new state object with the current tasks filtered to remove the task with the specified <code>id</code>.</p>
<h3 id="heading-step-4-how-to-create-the-redux-store">Step 4: How to create the Redux store</h3>
<p>Now that we have our basic setup ready, let's create a new file called <code>store.js</code> in the <code>src</code> directory. This is where you'll define your Redux store:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">"redux"</span>;
<span class="hljs-keyword">import</span> thunk <span class="hljs-keyword">from</span> <span class="hljs-string">"redux-thunk"</span>;
<span class="hljs-keyword">import</span> { composeWithDevTools } <span class="hljs-keyword">from</span> <span class="hljs-string">"redux-devtools-extension"</span>;

<span class="hljs-keyword">import</span> taskReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"./reducers/taskReducer"</span>;

<span class="hljs-keyword">const</span> store = createStore(
  taskReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store;
</code></pre>
<p>The code above sets up a Redux store by creating a new instance of the store using the <code>createStore</code> function. Then, the rootReducer – which combines all the application's reducers into a single reducer – is passed as an argument to <code>createStore</code>. </p>
<p>In addition, the code also uses two other libraries: <code>redux-thunk</code> and <code>redux-devtools-extension</code>. </p>
<p>The <code>redux-thunk</code> library allows you to write asynchronous actions, while the <code>redux-devtools-extension</code> library enables you to use the Redux DevTools browser extension to debug and inspect the state and actions in the store. </p>
<p>Finally, we export the store so we can use it in our application. We use the <code>composeWithDevTools</code> function to enhance the store with the ability to use the Redux DevTools extension, and the <code>applyMiddleware</code> function to apply the thunk middleware to the store."</p>
<h3 id="heading-step-5-how-to-connect-the-redux-store-to-the-application">Step 5: How to connect the Redux Store to the application</h3>
<p>To connect the Redux store to the ToDo application, we need to use the <code>Provider</code> component from the <code>react-redux</code> library.</p>
<p>First, we import the <code>Provider</code> function and the Redux store we created into our <code>main.jsx</code>. Then, we wrap our <code>App</code> component with the <code>Provider</code> function and pass the <code>store</code> as a prop. This makes the Redux store available to all the components inside the <code>App</code>.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./index.css"</span>;

<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">"./store"</span>;

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>
);
</code></pre>
<h3 id="heading-step-6-how-to-use-redux-devtools">Step 6: How to use Redux DevTools</h3>
<p>Once you've set up the Redux <code>&lt;Provider&gt;</code> in your application, you can start using the Redux DevTools extension. To get started with it, you'll need to download the Redux DevTools Extension for your browser. </p>
<p>After installation, the DevTools will add a new tab to your browser's Developer Tools specifically for Redux.</p>
<p><img src="https://i.imgur.com/QPPsZDT.gif" width="832" height="547" alt="QPPsZDT" loading="lazy"></p>
<p>Clicking on the "State" tab within the Redux DevTools will show you the entire state of your Redux store and any actions that have been dispatched and their payloads. </p>
<p>This can be incredibly useful when debugging your application, as you can inspect the state and actions in real-time.</p>
<h3 id="heading-step-7-how-to-set-up-redux-actions">Step 7: How to set up Redux Actions</h3>
<p>Now that we have everything set up, let's create our actions. As I mentioned before, actions represent something that happened in the application. For example, when a user adds a new task, it triggers an "add task" action. Similarly, when a user deletes a task, it triggers a "delete task" action.</p>
<p>To create the actions, create a new folder called "actions" in the <code>src</code> directory and then create a new file called <code>index.js</code>. This file will contain all of the action creators for our application.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> addTodo = <span class="hljs-function">(<span class="hljs-params">text</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">type</span>: <span class="hljs-string">"ADD_TASK"</span>,
    <span class="hljs-attr">payload</span>: {
      <span class="hljs-attr">id</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime(),
      <span class="hljs-attr">text</span>: text,
    },
  };
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> deleteTodo = <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">type</span>: <span class="hljs-string">"DELETE_TASK"</span>,
    <span class="hljs-attr">payload</span>: id,
  };
};
</code></pre>
<p>The above code exports two action creators: <code>addTodo</code> and <code>deleteTodo</code>. These functions return an object with a <code>type</code> property that describes the action that has occurred.</p>
<p>In the case of <code>addTodo</code>, the <code>type</code> property is set to <code>"ADD_TASK"</code>, indicating that a new task has been added. The <code>payload</code> property contains an object with the new task's <code>id</code> and <code>text</code> values. The <code>id</code> is generated using the <code>new Date().getTime()</code> method creates a unique identifier based on the current timestamp.</p>
<p>In the case of <code>deleteTodo</code>, the <code>type</code> property is set to <code>"DELETE_TASK"</code>, indicating that a task has been deleted. The <code>payload</code> property contains the <code>id</code> of the task to be deleted.</p>
<p>These action creators can be dispatched to the Redux store using the <code>dispatch()</code> method, which will trigger the corresponding reducer function to update the application state accordingly.</p>
<h3 id="heading-step-8-how-to-dispatch-actions">Step 8: How to dispatch actions</h3>
<p>Now that we have created the necessary actions, we can move on to creating the components that will dispatch these actions. </p>
<p>Let's create a new folder named "components" inside the <em>src</em> directory. Inside this folder, we will create two new files: <code>Task.jsx</code> and <code>TaskList.jsx</code>.</p>
<p>The <code>Task.jsx</code> component will be responsible for adding tasks. But before we proceed, we need to import the following into the file:</p>
<ul>
<li><em>addTodo action</em>: To add new tasks to the state.</li>
<li><em>useDispatch hook</em>: To dispatch the <code>addTodo</code> action.</li>
<li><em>useRef</em>: Allows us to obtain a reference to HTML elements.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useDispatch } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> { addTodo } <span class="hljs-keyword">from</span> <span class="hljs-string">"../actions"</span>;
</code></pre>
<p>Once we have imported these necessary components, we can proceed to write code for <code>Task.jsx</code>. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> Task = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> dispatch = useDispatch();
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNewTask</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> task = inputRef.current.value.trim();
    <span class="hljs-keyword">if</span> (task !== <span class="hljs-string">""</span>) {
      dispatch(addTodo(task));
      inputRef.current.value = <span class="hljs-string">""</span>;
    }
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"task-component"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"add-task"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Add task here..."</span>
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span>
          <span class="hljs-attr">className</span>=<span class="hljs-string">"taskInput"</span>
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{addNewTask}</span>&gt;</span>Add task<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Task;
</code></pre>
<p>In the code above, we created a component consisting of an input field and a button. When a user clicks on the "Add task" button, the <code>addNewTask</code> function is executed. This function uses the <code>useRef</code> hook to obtain the input field's value, removes any leading or trailing whitespaces, and then dispatches the <code>addTodo</code> action with the new task as the payload.</p>
<p>Now, let's move on to the <code>TaskList.jsx</code> component, responsible for rendering the list of tasks and handling task deletions. To achieve this, we need to import the following:</p>
<ul>
<li>The <strong>useSelector hook</strong> provides access to the state from the Redux store.</li>
<li>The <strong>deleteTodo action</strong>, is responsible for removing a task from the list of tasks in the Redux store.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useSelector, useDispatch } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;
<span class="hljs-keyword">import</span> { deleteTodo } <span class="hljs-keyword">from</span> <span class="hljs-string">"../actions"</span>;
</code></pre>
<p>We will now write code for <code>TaskList.jsx</code> that maps over the tasks array and renders each task:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useSelector, useDispatch } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> { deleteTodo } <span class="hljs-keyword">from</span> <span class="hljs-string">'../actions'</span>;

<span class="hljs-keyword">const</span> TaskList = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> tasks = useSelector(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.tasks);
  <span class="hljs-keyword">const</span> dispatch = useDispatch();

  <span class="hljs-keyword">const</span> handleDelete = <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
    dispatch(deleteTodo(id));
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"tasklist"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"display-tasks"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Your tasks:<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"tasks"</span>&gt;</span>
          {tasks.map((task) =&gt; (
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"task"</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{task.id}</span>&gt;</span>
              {task.text}
              <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
                <span class="hljs-attr">className</span>=<span class="hljs-string">"delete-btn"</span>
                <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> handleDelete(task.id)}
              &gt;
                delete
              <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          ))}
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> TaskList;
</code></pre>
<p>Here, the component loops over each task in the tasks array and displays text and a delete button. When the user clicks the delete button, the <code>handleDelete</code> function is called, dispatching the <code>deleteTodo</code> action with the task's <code>id</code> as the payload.</p>
<p>Finally, import the components into your <code>App.jsx</code> file and render them.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Task <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Task"</span>;
<span class="hljs-keyword">import</span> TaskList <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/TaskList"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Task</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">TaskList</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h3 id="heading-step-9-styling">Step 9: Styling</h3>
<p>For styling, copy the contents of this <a target="_blank" href="https://gist.githubusercontent.com/dboatengg/ea07e95167aec1af97084651128ea8e9/raw/d5b0e5611c4a82e46ad4bc2f33defefd4ce9937a/index.css">gist</a> and paste it into your <code>index.css</code> file. The focus of this guide is only on functionality and not on styling. Therefore, only basic styles were included to ensure the application looked presentable.</p>
<h3 id="heading-final-result">Final Result</h3>
<p>After implementing everything, the final result of our ToDo List application should look something like this:</p>
<p><img src="https://i.imgur.com/AACNPOW.gif" width="680" height="350" alt="AACNPOW" loading="lazy"></p>
<p>As shown above, we can add tasks by entering texts in the input field and clicking the "Add task" button. We can also delete tasks by clicking the "delete" button next to each task.</p>
<p>The state and actions of the application can also be easily tracked and inspected using Redux DevTools. This feature helps debug and understand how the app works under the hood.</p>
<p>With that, you now have a fully functional ToDo application powered by Redux! The source code for the app is available on this <a target="_blank" href="https://github.com/dboatengg/redux-tutorial">GitHub repository</a>.</p>
<p>Finally, it's important to note that an application's state is stored in memory when using Redux. Therefore, the state will be lost if a user refreshes the page or navigates away from the app.</p>
<p>So, to keep information even after a user leaves or closes the page, you need to store that information somewhere else outside of the app's memory. Various techniques, such as local or server-side storage, can be used to accomplish this.</p>
<p>Congratulations! You now have a good grasp of how to integrate Redux into your React applications. In the next section, we will explore Redux Toolkit and discover how it can simplify the process of writing Redux code with less effort.</p>
<h2 id="heading-how-to-use-redux-toolkit">How to Use Redux Toolkit</h2>
<p>Writing Redux code can become complex and verbose, particularly as the size of an application grows. As the number of reducers and actions increase, it can become challenging to manage the different pieces and keep track of everything.</p>
<p>Fortunately, Redux Toolkit provides a solution to this problem. It gives a more streamlined and efficient way to manage the state of your application by abstracting away some of the more complex and repetitive aspects of Redux, such as creating reducers and actions.</p>
<h3 id="heading-advantages-of-redux-toolkit">Advantages of Redux Toolkit</h3>
<p>Redux Toolkit provides several advantages over traditional Redux:</p>
<ul>
<li>It is easier to set up and requires fewer dependencies.</li>
<li>Reduces boilerplate code by allowing the creation of a single file known as "slice" that combines actions and reducers.</li>
<li>Provides sensible defaults for commonly used features, such as Redux Thunk and Redux DevTools. This means that you don't have to spend time configuring these features yourself, as they are already built into Redux Toolkit.</li>
<li>It uses the immer library under the hood, which enables direct state mutation and eliminates the need for manually copying the state <code>{...state}</code> with every reducer.</li>
</ul>
<p>In the next sections, we will explore how to use Redux Toolkit to simplify the Redux code for the ToDo application we built earlier.</p>
<h3 id="heading-how-to-set-up-redux-toolkit">How to set up Redux Toolkit</h3>
<p>To use Redux Toolkit in your React application, you need to install two dependencies: <code>@reduxjs/toolkit</code> and <code>react-redux</code>. </p>
<p>The <code>@reduxjs/toolkit</code> package provides the necessary tools to simplify Redux development, while <code>react-redux</code> is needed to connect your Redux store to your React components. </p>
<pre><code>npm install @reduxjs/toolkit react-redux
</code></pre><h3 id="heading-how-to-create-a-slice">How to create a slice</h3>
<p>Once you have installed the needed dependencies, create a new "slice" using the <code>createSlice</code> function. A slice is a portion of the Redux store that is responsible for managing a specific piece of state.</p>
<p>Think of the Redux store as a cake, where each slice represents a specific piece of data in the store. By creating a slice, you can define the behaviour of the state in response to particular actions using reducer functions.</p>
<p>To create a slice to manage our ToDo application, create a new file named <code>src/features/todo/todoSlice.js</code> and add the following code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createSlice } <span class="hljs-keyword">from</span> <span class="hljs-string">"@reduxjs/toolkit"</span>;

<span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">tasks</span>: [],
};

<span class="hljs-keyword">const</span> todoSlice = createSlice({
  <span class="hljs-attr">name</span>: <span class="hljs-string">"todo"</span>,
  initialState,
  <span class="hljs-attr">reducers</span>: {
    <span class="hljs-attr">addTodo</span>: <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
      state.tasks.push({ <span class="hljs-attr">id</span>: <span class="hljs-built_in">Date</span>.now(), <span class="hljs-attr">text</span>: action.payload });
    },
    <span class="hljs-attr">deleteTodo</span>: <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
      state.tasks = state.tasks.filter(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> task.id !== action.payload);
    },
  },
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { addTodo, deleteTodo } = todoSlice.actions;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> todoSlice.reducer;
</code></pre>
<p>The above code defines a slice named <code>todoSlice</code>, with an <code>initialState</code> object that contains an empty array of tasks. </p>
<p>The <code>reducers</code> object defines two reducer functions: <code>addTask</code> and <code>deleteTask</code>. <code>addTask</code> pushes a new task object into the <code>tasks</code> array, and <code>deleteTask</code> removes a task from the <code>tasks</code> array based on its <code>id</code> property.</p>
<p>The <code>createSlice</code> function automatically generates action creators and action types based on the names of the reducer functions you provide. So you don't have to define the action creators yourself manually.</p>
<p>The <code>export</code> statement exports the generated action creators, which can be used in other parts of your app to dispatch actions to the slice.</p>
<p>And finally, the <code>todoSlice.reducer</code> function handles all actions automatically generated based on the reducer objects provided to the <code>createSlice</code> function. By exporting it as the default, you can combine it with other reducers in your application to create a complete Redux store.</p>
<h3 id="heading-how-to-set-up-redux-store">How to set up Redux Store</h3>
<p>Creating a Redux store is much simpler with Redux Toolkit. </p>
<p>The most basic way to create a store is to use the <code>configureStore()</code> function, which automatically generates a root reducer for you by combining all the reducers defined in your application. </p>
<p>To create a store for the application, add a file named <code>src/store.js</code> and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { configureStore } <span class="hljs-keyword">from</span> <span class="hljs-string">"@reduxjs/toolkit"</span>;
<span class="hljs-keyword">import</span> todoReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"./features/todo/todoSlice"</span>;

<span class="hljs-keyword">const</span> store = configureStore({
  <span class="hljs-attr">reducer</span>: {
    <span class="hljs-attr">todo</span>: todoReducer,
  },
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store;
</code></pre>
<p>In this example, we first import the <code>configureStore</code> function from the <code>@reduxjs/toolkit</code> package, and the  <code>todoReducer</code> function from a separate file.</p>
<p>Then, we create a <code>store</code> object by calling <code>configureStore</code> and passing it an object with a <code>reducer</code> property. The <code>reducer</code> property is an object that maps reducer slice names to their corresponding reducer functions. In this case, we have one reducer slice called <code>todo</code>, and its corresponding reducer function is <code>todoReducer</code>.</p>
<p>Finally, we export the <code>store</code> object so that it can be imported and used in other parts of the application.</p>
<h3 id="heading-how-to-provide-the-redux-store-to-react">How to provide the Redux store to React</h3>
<p>To make your Redux store available to the React components in your application, import the Provider component from the <code>react-redux</code> library and wrap your root component (usually <code>&lt;App&gt;</code>) with it. </p>
<p>The Provider component takes in the store as a prop and passes it down to all the child components that need access to it.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App.jsx"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./index.css"</span>;

<span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">"./store.js"</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-redux"</span>;

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>
);
</code></pre>
<h3 id="heading-create-components">Create components</h3>
<p>You can now create React components such as <code>Task.jsx</code> and <code>TaskList.jsx</code> that use the <code>useSelector</code> hook to access the current state from the store. Similarly, you can use the <code>useDispatch</code> hook to dispatch actions to update the store, just as you did in plain Redux. </p>
<p>You should now have the same app as before with a few updates from Redux Toolkit and a lot less code to maintain.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you've followed along with this tutorial, you should now have a solid understanding of Redux, both the traditional approach and the simplified version using Redux Toolkit. </p>
<p>I hope you found this article helpful and informative. I know it was a lot of material to cover, but I hope it serves as a comprehensive resource for beginners and intermediate learners seeking to learn Redux. </p>
<p>If you want to experiment with the code we've covered in this article, you can access it in the <a target="_blank" href="https://github.com/dboatengg/redux-tutorial">GitHub repository</a> provided. Feel free to use it as a starting point for your own applications or as a reference as you continue to learn and explore the world of Redux.</p>
<p>Thank you for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the React Context API in Your Projects ]]>
                </title>
                <description>
                    <![CDATA[ Managing state is an essential part of developing applications in React. A common way to manage state is by passing props. Passing props means sending data from one component to another. It's a good way to make sure that data gets to the right place ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/context-api-in-react/</link>
                <guid isPermaLink="false">66bd904bdc6141cf21aaada1</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React context ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Wed, 29 Mar 2023 20:04:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/context-api-cover-main.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Managing state is an essential part of developing applications in React. A common way to manage state is by passing props. Passing props means sending data from one component to another. It's a good way to make sure that data gets to the right place in a React application. </p>
<p>But it can be annoying to pass props when you have to send the same data to lots of components or when components are far away from each other. This can make an application slower and harder to work with.</p>
<p>Fortunately, React provides a built-in feature known as the context API that helps  “teleport” data to the components that need it without passing props. </p>
<p>In this article, we'll explore how the context API works and how to use it effectively in your React applications.</p>
<h2 id="heading-the-problem-with-passing-props">The Problem with Passing Props</h2>
<p>In React, passing props is a fundamental concept that enables a parent component to share data with its child components as well as other components within an application. </p>
<p>In many cases, passing props can be an effective way to share data between different parts of your application. But passing props down a chain of multiple components to reach a specific component can make your code overly cumbersome. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-198.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of passing props from parent to children</em></p>
<p>From the above diagram, to pass data down to the component "Child B", we need to pass it down through all the intermediate components, even if those components don't actually use the data themselves. This is what is referred to as "prop drilling." </p>
<p>Prop drilling can make your code more difficult to read and maintain, and can also make it harder to refactor your components later on.</p>
<p>This is where the Context API comes in. With Context API, you can store data at the top level of the component tree and make it available to all other components that need it without passing props.</p>
<h2 id="heading-how-the-context-api-works">How the Context API Works</h2>
<p>Context API allows data to be passed through a component tree without having to pass props manually at every level. This makes it easier to share data between components.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/image-197.png" alt="Image" width="600" height="400" loading="lazy">
<em>A diagram illustrating how Context API works</em></p>
<p>For example, let’s say you have a shopping app with a component that shows a user’s shopping cart, and another component that shows the user’s order history.</p>
<p>With Context API, you can create a “context” that holds the user’s shopping information, like their cart and order history. Then, you can use that context in both the shopping cart and the order history component, without having to pass the information down through props.</p>
<p>It’s like having a big box that holds all the things you need for your shopping trip. You can take things out of the box when you need them, and put them back in when you’re done. </p>
<p>Basically, Context API consists of two main components: the context provider and the context consumer. The provider is responsible for creating and managing the context, which holds the data to be shared between components. On the other hand, the consumer is used to access the context and its data from within a component. </p>
<p>In the example given, the provider will create the context that holds the user's shopping information, while the consumer components (shopping cart and order history) will access that context to retrieve the data they need. This avoids the need to pass the information down through props, making your code more efficient and easier to manage.</p>
<h2 id="heading-how-to-get-started-with-the-context-api">How to Get Started with the Context API</h2>
<p>To start using the Context API in your applications, you'll need to follow a few simple steps:</p>
<h3 id="heading-1-create-a-context-object">1. Create a Context Object</h3>
<p>First, you need to create a context object using the <code>createContext</code> function from the 'react' library. This context object will hold the data that you want to share across your application. </p>
<p>Create a new file named <code>MyContext.js</code> in the <code>src</code> folder and add the following code to create a context object:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> MyContext = createContext(<span class="hljs-string">""</span>);
</code></pre>
<p>In the above code, we're importing <code>createContext</code> from React and using it to create a new context object named "MyContext". Then, we are exporting the context object so that we can use it in other parts of our application.</p>
<h3 id="heading-2-wrap-components-with-a-provider">2. Wrap Components with a Provider</h3>
<p>Once you've created a context object, you need to wrap the components that need access to the shared data with a Provider component. The Provider component accepts a "value" prop that holds the shared data, and any component that is a child of the Provider component can access that shared data.</p>
<p>It's important to note that the Provider component should be wrapped around the top-level component in an application to ensure that all child components have access to the shared data.</p>
<p>Here's an example that demonstrates how to wrap components with a Provider in Context API:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Create a parent component that wraps child components with a Provider</span>

<span class="hljs-keyword">import</span> { useState, React } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { MyContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"./MyContext"</span>;
<span class="hljs-keyword">import</span> MyComponent <span class="hljs-keyword">from</span> <span class="hljs-string">"./MyComponent"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [text, setText] = useState(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">MyContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">text</span>, <span class="hljs-attr">setText</span> }}&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">MyContext.Provider</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In this example, we have a parent component called App. This component has a state variable called "text", which is initially set to an empty string. We've also defined a function called <code>setText</code> that can be used to update the value of <code>text</code>.</p>
<p>Inside the return statement of the App component, we've wrapped the children of this component with the provider component ("MyContext.Provider"). Then we've passed an object to the value prop of the provider component that contains "text" and "setText" values.</p>
<h3 id="heading-3-consume-the-context">3. Consume the Context</h3>
<p>Now that we've created the provider component, we need to consume the context in other components. To do this, we use the "useContext" hook from React. </p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { MyContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./MyContext'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { text, setText } = useContext(MyContext);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{text}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setText('Hello, world!')}&gt;
        Click me
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In this example, we've used the useContext hook to access the "text" and "setText" variables that were defined in the provider component.</p>
<p>Inside the return statement of "MyComponent", we've rendered a paragraph element that displays the value of <code>text</code>. We've also rendered a button that, when clicked, will call the <code>setText</code> function to update the value of <code>text</code> to "Hello, world!".</p>
<p><img src="https://i.imgur.com/a191j3C.gif" width="716" height="472" alt="a191j3C" loading="lazy"></p>
<p>And that's it! This is how you can use the Context API in your React application. </p>
<p>By creating a context object, defining a provider component, and consuming the context in other components, you can share data across your application in a simple and efficient way.</p>
<h2 id="heading-use-cases-of-context-api">Use Cases of Context API</h2>
<p>Here are some real-world use cases of Context API.</p>
<ol>
<li><strong>Theming:</strong> You can use Context API to store the current theme of your application and make it available to all components. This way, whenever the user switches the theme (such as enabling dark mode), all components will be updated with the new theme.</li>
<li><strong>User Authentication:</strong> You can also use Context API to store a user's authentication status and pass it down to all the components that need it. This way, you can easily restrict access to certain parts of your application based on the user's authentication status.</li>
<li><strong>Multilingual Support:</strong> You can store the current language of your application in the context and pass it down to all the components that need it. This way, you can easily switch between different languages without having to pass the language down as props to all the components.</li>
<li><strong>Accessing data from external sources:</strong> Finally, you can use the Context API to store data retrieved from external sources such as APIs or databases and make it available to all components. This can simplify your code and make it easier to manage data across your application.</li>
</ol>
<p>Overall, Context API provides a flexible and efficient way to manage state data across your application, and it can be particularly useful for managing global data that needs to be shared between multiple components.</p>
<h2 id="heading-best-practices-for-context-api">Best Practices for Context API</h2>
<p>As with any tool, there are best practices and common pitfalls to keep in mind when using the Context API in your projects. Here are some tips for effective use of the Context API:</p>
<ol>
<li>Use a separate file to define your Context: It's a good practice to define your context object in a separate file to keep your code organized and easy to maintain. </li>
<li>Keep Context API limited to global state management only: It's best to use the Context API for managing state that needs to be accessed across multiple components in your application. Avoid using it for state that only needs to be accessed within a single component, as it can lead to unnecessary complexity and performance issues.</li>
<li>Use context providers sparingly: While context providers can be a powerful tool for managing global state, it's generally a good idea to use them sparingly. Instead, consider using props to pass data down through your component tree whenever possible.</li>
<li>Use default values: When creating a new context, it's a good idea to provide a default value that will be used if no provider is present. This can help prevent unexpected errors and make your code more robust. Note that, for the project we did above, we used an empty string as the default value for the context object. </li>
</ol>
<h2 id="heading-recap">Recap</h2>
<p>In this article, we explored the React Context API, a powerful tool for managing state in React applications.</p>
<p>We have walked through the basics of the Context API, including creating a context, creating a Provider component to pass data to child components, and consuming data in other component using the <code>useContext</code> hook.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you're interested in exploring how to implement a light/dark mode theme in your own React projects using the Context API, I've created a simple website that demonstrates how to do just that. You can find the code for the project on my <a target="_blank" href="https://github.com/dboatengg/context-api-tutorial">GitHub</a>. </p>
<p>By exploring the code and experimenting with your own modifications, you'll be well on your way to mastering the Context API and unlocking its full potential in your own projects. </p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build Forms in React ]]>
                </title>
                <description>
                    <![CDATA[ Forms play an essential role in modern web applications. They enable users to share information, complete tasks and provide feedback.  Without forms, many of the tasks that we take for granted on the web, such as logging in, signing up, or making pur... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-forms-in-react/</link>
                <guid isPermaLink="false">66bd904edc6141cf21aaada4</guid>
                
                    <category>
                        <![CDATA[ forms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Fri, 10 Mar 2023 17:43:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/pexels-rodnae-productions-7821577.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Forms play an essential role in modern web applications. They enable users to share information, complete tasks and provide feedback. </p>
<p>Without forms, many of the tasks that we take for granted on the web, such as logging in, signing up, or making purchases, would not be possible.</p>
<p>As such, learning how to create effective and user-friendly forms is essential for developers looking to build engaging and interactive web applications.</p>
<p>With its extensive collection of built-in hooks, React provides several features and techniques for creating and managing forms, including state management, event handling, and form validation.</p>
<p>The purpose of this guide is to provide a comprehensive and in-depth look at creating forms in React. </p>
<h2 id="heading-getting-started">Getting Started...</h2>
<p>In React, there are two ways of handling form data:</p>
<ul>
<li><strong>Controlled Components:</strong> In this approach, form data is handled by React through the use of hooks such as the <code>useState</code> hook.</li>
<li><strong>Uncontrolled Components:</strong> Form data is handled by the Document Object Model (DOM) rather than by React. The DOM maintains the state of form data and updates it based on user input.</li>
</ul>
<p>To better understand the difference between controlled and uncontrolled components, consider there are two ways of riding a bike.</p>
<p>In the first approach, you let the bike take control. You sit on the bike and let it decide the direction and speed. You might try to make it go in a certain direction by leaning your body, but ultimately, the bike decides where to go.</p>
<p>This is similar to uncontrolled components in React. You place a form element in the component, and the DOM takes control of it. The DOM decides the state of the input element and updates it based on a user's input.</p>
<p>In the second approach, you take control of the bike. You hold the handlebars and pedal, and you decide where to go and how fast to ride. You can easily slow down or speed up as needed.</p>
<p>This is similar to controlled components where a React component takes control of the form data, and maintains the state of form elements. The component decides when and how to update the state, and it re-renders itself based on the state changes.</p>
<p>In the upcoming sections, we will expound upon the distinction between controlled and uncontrolled components and provide practical examples to illustrate how each operates.</p>
<h2 id="heading-controlled-components-in-react">Controlled Components in React</h2>
<p>In React, a controlled component is a component where form elements derive their value from a React state.</p>
<p>When a component is controlled, the value of form elements is stored in a state, and any changes made to the value are immediately reflected in the state.</p>
<p>To create a controlled component, you need to use the <code>value</code> prop to set the value of form elements and the <code>onChange</code> event to handle changes made to the value.</p>
<p>The <code>value</code> prop sets the initial value of a form element, while the <code>onChange</code> event is triggered whenever the value of a form element changes. Inside the <code>onChange</code> event, you need to update the state with the new value using a state update function.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {useState} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span>  <span class="hljs-title">ControlledComponent</span>(<span class="hljs-params"></span>)  </span>{
    <span class="hljs-keyword">const</span>  [inputValue, setInputValue] =  useState(<span class="hljs-string">''</span>);

    <span class="hljs-keyword">const</span>  handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        setInputValue(event.target.value);
    };

<span class="hljs-keyword">return</span>  (
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Input Value:
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span>  <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Input Value: {inputValue}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
)};
</code></pre>
<p>In this example:</p>
<p>The <code>useState</code> hook defines a state variable (inputValue) and a state update function (setInputValue).</p>
<p>The <code>value</code> prop sets the initial value of the input element to the value of <code>inputValue</code>.</p>
<p>Also, the <code>onChange</code> event handles changes made to the input value. The <code>handleChange</code> function updates the <code>inputValue</code> state with the new value of the input element, and the updated value is immediately reflected in the state and displayed on the screen.</p>
<p><img src="https://i.imgur.com/N77Ohpv.gif" width="700" height="300" alt="N77Ohpv" loading="lazy"></p>
<p>As the user types into the input field, the <code>handleChange</code> function updates the state variable using the "setInputValue" function. The component is then re-rendered, and the input field's <code>value</code> attribute is updated to reflect the new value of <code>inputValue</code>.</p>
<p>The value of the input field and the text displayed below it are always in sync, making it a controlled component.</p>
<h3 id="heading-how-to-handle-dropdowns-and-checkboxes-in-controlled-components">How to handle dropdowns and checkboxes in Controlled Components</h3>
<p>Just like with input elements, the value of a dropdown can be set by using the <code>value</code> prop in conjunction with the <code>onChange</code> event handler to update the state of the component.</p>
<p>For example, to handle a dropdown menu, you can define the initial value of the dropdown menu within the state of the component, then update the state when the value of the dropdown changes:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dropdown</span>(<span class="hljs-params"></span>)  </span>{
    <span class="hljs-keyword">const</span> [selectedOption, setSelectedOption] = useState(<span class="hljs-string">"option1"</span>);

    <span class="hljs-keyword">const</span>  handleDropdownChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        setSelectedOption(event.target.value);
    };

<span class="hljs-keyword">return</span>  (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
            Select an option:
                <span class="hljs-tag">&lt;<span class="hljs-name">select</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">{selectedOption}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleDropdownChange}</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">"option1"</span>&gt;</span>Option 1<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">"option2"</span>&gt;</span>Option 2<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">"option3"</span>&gt;</span>Option 3<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Selected option: {selectedOption}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}
</code></pre>
<p><img src="https://i.imgur.com/5cjbAeO.gif" width="700" height="300" alt="5cjbAeO" loading="lazy"></p>
<p>Similarly, you can handle checkboxes by setting the <code>checked</code> prop of the checkbox input element based on the state of a component, and then updating the state when a checkbox is clicked.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Checkbox</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [isChecked, setIsChecked] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setIsChecked(event.target.checked);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"color"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"color"</span> <span class="hljs-attr">checked</span>=<span class="hljs-string">{isChecked}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}/</span>&gt;</span>
        Blue
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

      {isChecked &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Blue is selected!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Checkbox;
</code></pre>
<p>In this example, we have defined a state variable <code>isChecked</code> to keep track of whether the checkbox is checked or not. When the checkbox is clicked, the <code>handleChange</code> function is called, and it updates the <code>isChecked</code> state variable to a new value (true or false.).</p>
<p>The <code>isChecked</code> variable controls the <code>checked</code> attribute of the checkbox input and conditionally renders a message indicating that the checkbox is selected.</p>
<p><img src="https://i.imgur.com/81zMRzO.gif" width="700" height="300" alt="81zMRzO" loading="lazy"></p>
<h3 id="heading-how-to-handle-multiple-form-fields">How to handle multiple form fields</h3>
<p>When working with forms in React, it's common to have several form elements, such as text inputs, checkboxes, radio buttons, and others. </p>
<p>To manage the state of these form elements, you can define the values for the input fields as an object using a single state variable and update each respective state variable using the <code>onChange</code> event.</p>
<p>As an example, suppose you wish to create a form with the following fields:</p>
<ul>
<li>Text input for the user's name</li>
<li>An email field for the user's email</li>
<li>A textarea field for the user's message</li>
</ul>
<p>Here's how you could handle these fields:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Multiple</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [formData, setFormData] = useState({<span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,<span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,<span class="hljs-attr">message</span>: <span class="hljs-string">""</span>});

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, value } = event.target;
    setFormData(<span class="hljs-function">(<span class="hljs-params">prevFormData</span>) =&gt;</span> ({ ...prevFormData, [name]: value }));
  };

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(<span class="hljs-string">`Name: <span class="hljs-subst">${formData.name}</span>, Email: <span class="hljs-subst">${formData.email}</span>, Message: <span class="hljs-subst">${formData.message}</span>`</span>
    );
};

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"name"</span>&gt;</span>Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{formData.name}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}/</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{formData.email}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}/</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"message"</span>&gt;</span>Message:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"message"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"message"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{formData.message}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}/</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p><img src="https://i.imgur.com/4ln01Wq.gif" width="900" height="450" alt="4ln01Wq" loading="lazy"></p>
<p>In the example code:</p>
<p>The <code>useState</code> hook defines a state object named <code>formData</code> that contains three properties: <code>name</code>, <code>email</code>, and <code>message</code>, each initialized to an empty string.</p>
<p>The <code>handleChange</code> function is called whenever a user types in one of the form fields. It extracts the <code>name</code> and <code>value</code> of the form field that has changed using the <code>event.target</code> object and then updates the <code>formData</code> state variable using the <code>setFormData</code> function.</p>
<p>The <code>setFormData</code> function uses the spread operator (<code>...</code>) to copy the previous <code>formData</code> object. Then it updates the value of the changed form field by setting its value prop with the new value.</p>
<p>By using an object to manage form data, we can easily keep track of the values of multiple form elements. This makes it easier to manage and manipulate the state of our form data, especially when dealing with complex forms with many form elements.</p>
<h3 id="heading-how-to-validate-form-input">How to validate form input</h3>
<p>Validating forms refers to the process of checking user input data to ensure that it meets specific criteria or requirements before it is submitted to a server or used in some other way.</p>
<p>Form validation can take various forms, depending on the type and complexity of the data being collected. Common types of form validation include:</p>
<ul>
<li>Required field validation: Checking that required fields are not left empty.</li>
<li>Format validation: Ensuring that input data is in the correct format (for example, email addresses, phone numbers, and so on).</li>
<li>Length validation: Checking that input data is within a certain length range.</li>
<li>Pattern validation: Checking that input data matches a specific pattern.</li>
</ul>
<p>Common methods for form validation include using built-in HTML validation attributes like <code>required</code>, <code>minlength</code>, and <code>maxlength</code>, as well as using React to perform custom validation logic.</p>
<p>As an example, suppose we have a form with an input field that requires a minimum of 5 characters. We can use state to track the value of the input field and display an error message if the length of the value is less than 5.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyForm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [inputValue, setInputValue] = useState(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">const</span> [inputError, setInputError] = useState(<span class="hljs-literal">null</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleInputChange</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-keyword">const</span> value = event.target.value;
    setInputValue(value);

    <span class="hljs-keyword">if</span> (value.length &lt; <span class="hljs-number">5</span>) {
      setInputError(<span class="hljs-string">'Input must be at least 5 characters'</span>);
    } <span class="hljs-keyword">else</span> {
      setInputError(<span class="hljs-literal">null</span>);
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleSubmit</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault();
    <span class="hljs-keyword">if</span> (inputValue.length &gt;= <span class="hljs-number">5</span>) {
      <span class="hljs-comment">// submit form</span>
    } <span class="hljs-keyword">else</span> {
      setInputError(<span class="hljs-string">'Input must be at least 5 characters'</span>);
    }
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Fruit:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      {inputError &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> '<span class="hljs-attr">red</span>' }}&gt;</span>{inputError}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p><img src="https://i.imgur.com/Dfm7dtp.gif" width="700" height="300" alt="Dfm7dtp" loading="lazy"></p>
<p>In this example, we have a simple form that allows the user to input a fruit name. The form has two states:</p>
<ul>
<li><code>inputValue</code>: Represents the current value of the input field</li>
<li><code>inputError</code>: Represents any errors that may arise during form validation.</li>
</ul>
<p>The <code>handleInputChange</code> function is called every time a user types a character in the input field. It updates the <code>inputValue</code> state to reflect the current value of the input field, and then checks whether the value is at least 5 characters long.</p>
<p>If the value is less than 5 characters, it sets the <code>inputError</code> state to the appropriate error message. Otherwise, it sets the <code>inputError</code> state to <code>null</code> (indicating that there are no errors).</p>
<h2 id="heading-uncontrolled-components-in-react">Uncontrolled Components in React</h2>
<p>Uncontrolled components in React refer to form elements whose state is not managed by React. Instead, their state is handled by the browser's DOM.</p>
<p>For instance, let's say you have a form that consists of a text input field, a select box, and a checkbox. In a controlled component, you would create a state for each form element and write event handlers to update the state whenever the user interacts with any of the form elements.</p>
<p>In contrast, an uncontrolled component allows the browser to handle the form elements' state. When a user enters text into a text input field or selects an option from a select box, the browser updates the DOM's state for that element automatically.</p>
<p>To get the value of an uncontrolled form element, you can use a feature called "ref". "Refs" provide a way to access the current value of DOM elements. You can create a "ref" using the <code>useRef</code> hook, then attach it to the form element you want to access. This allows you to retrieve the current value of an element at any time, without needing to manage its state in your React component.</p>
<p>Here's an example of an uncontrolled component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Uncontrolled</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> selectRef = useRef(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> checkboxRef = useRef(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleSubmit</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Input value:"</span>, inputRef.current.value);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Select value:"</span>, selectRef.current.value);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Checkbox value:"</span>, checkboxRef.current.checked);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Name:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Favorite color:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{selectRef}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"red"</span>&gt;</span>Red<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"green"</span>&gt;</span>Green<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"blue"</span>&gt;</span>Blue<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Do you like React?
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{checkboxRef}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p><img src="https://i.imgur.com/4zXvzMm.gif" width="900" height="400" alt="4zXvzMm" loading="lazy"></p>
<p>In this example:</p>
<p>We have a form that contains a text input field, a select box, and a checkbox. Instead of creating state for each form element and writing event handlers to update the state, we're using uncontrolled components. This means that the browser is responsible for managing the state of the form elements.</p>
<p>When a user interacts with a form element, the browser automatically updates the DOM's state for that element. And to retrieve the current values of each form element, we're using the <code>useRef</code> hook.</p>
<p>Uncontrolled components can be useful in certain situations, such as when you need to integrate with third-party libraries or when you don't need to manipulate the form data.</p>
<p>Overall, uncontrolled components are a simpler approach to working with forms in React, and they can make your code more concise and easier to read. But it's important to note that using <code>ref</code> to access form element values can make your code harder to test and maintain, so use them judiciously.</p>
<h2 id="heading-how-to-use-react-component-libraries">How to Use React Component Libraries</h2>
<p>Creating forms in React can be overwhelming, especially if you're new to the framework. You need to manage form state, handle user input, validate input data and more.</p>
<p>But the good news is that there are third-party libraries available to make everything easier for you.</p>
<p>These libraries can help simplify your form creation process. They provide a wide range of features including form validation, input masking, submission handling, error handling, and more. This makes it much easier to create forms that are both user-friendly and functional.</p>
<p>Some popular form libraries include:</p>
<ul>
<li>Formik</li>
<li>Redux Form</li>
<li>React Hook Form</li>
<li>Yup.</li>
</ul>
<p>In this section, we'll focus on learning how to use the <strong>React Hook Form</strong> library.</p>
<h3 id="heading-how-to-use-react-hook-form">How to use React Hook Form</h3>
<p>React Hook Form is a lightweight library for managing forms in React applications. Whether you need to create a simple contact form or a complex multi-step form, React Hook Form can help simplify your form creation process.</p>
<h4 id="heading-installation">Installation</h4>
<p>Getting started with React Hook Form is straightforward and requires only a few steps. First, you'll need to install the library in your project. You can do this using <code>npm</code> by running the following command:</p>
<pre><code class="lang-npm">npm install react-hook-form
</code></pre>
<p>Alternatively, you can use yarn to install React Hook Form:</p>
<pre><code class="lang-yarn">yarn add react-hook-form
</code></pre>
<p>Once you've installed the library, you need to import the <code>useForm</code> hook from the <code>react-hook-form</code> package in your component.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span>  { useForm }  <span class="hljs-keyword">from</span>  <span class="hljs-string">"react-hook-form"</span>;
</code></pre>
<p>By importing the <code>useForm</code> hook, you can start using React Hook Form to manage forms in your application.</p>
<p>The <code>useForm</code> hook provides several functions and properties that you can use to manage your form:</p>
<ul>
<li><code>register</code>: This function is used to register form fields with React Hook Form.</li>
<li><code>handleSubmit</code>: This is used to handle form submissions. It takes a callback function that is called when the form is submitted.</li>
<li><code>errors</code>: This represents an object containing any validation errors that occur when a form is submitted.</li>
<li><code>watch</code>: This function is used to watch for changes to specific form fields. It takes an array of form field names and returns the current value of those fields.</li>
</ul>
<p>These are just a few examples of the functions and properties the useForm hook provides. You can find the complete list of functions and properties in the React Hook Form <a target="_blank" href="https://www.react-hook-form.com/api/useform/">documentation</a>.</p>
<h4 id="heading-how-to-set-up-the-form">How to set up the form</h4>
<p>After importing the <code>useForm</code> hook, you can invoke it to get access to the functions and properties that it provides:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> { register, handleSubmit, <span class="hljs-attr">formState</span>:{errors} } = useForm();
</code></pre>
<p>In the above code, we're using destructuring to extract the <code>register</code>, <code>handleSubmit</code>, and <code>errors</code> properties from the <code>useForm</code> hook.</p>
<h4 id="heading-how-to-register-form-fields">How to register form fields</h4>
<p>The next step is to register form fields using the <code>register</code> function. The <code>register</code> function takes two parameters:</p>
<ul>
<li><code>name</code>: The name of the form field.</li>
<li><code>validationOptions</code>: An optional object containing validation rules you can apply to a form field.</li>
</ul>
<p>Here's an example of registering an input field and adding a validation rule that it is a required field.</p>
<pre><code class="lang-jsx">&lt;input name=<span class="hljs-string">"firstName"</span> {...register(<span class="hljs-string">"firstName"</span>, { <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> })} /&gt;
</code></pre>
<h4 id="heading-how-to-handle-form-submission">How to handle form submission</h4>
<p>To handle form submission, you can use the <code>handleSubmit</code> function.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data);

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
  // form fields
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
</code></pre>
<p>In this example, we pass the <code>onSubmit</code> function to the <code>handleSubmit</code> function. The <code>onSubmit</code> function will be called when the form is submitted and will receive an object containing the values of each form field.</p>
<h4 id="heading-how-to-display-validation-errors">How to display validation errors</h4>
<p>You can use the <code>errors</code> object to display any validation errors.</p>
<pre><code class="lang-jsx">&lt;input {...register(<span class="hljs-string">"firstName"</span>, { <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> })} /&gt;
{errors.firstName &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This field is required<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>}
</code></pre>
<p>In the above code, we're using the <code>errors</code> object to display a validation error message if the <code>firstName</code> field is not filled out. We can also display error messages for other validation rules, such as minimum and maximum lengths, regular expressions, and more.</p>
<h4 id="heading-how-to-put-it-all-together">How to put it all together</h4>
<p>With a basic understanding of React Hook Form, let's now put everything into practice and create a simple form with two fields: <code>email</code> and <code>password</code>. We'll require both fields to be filled out and validate the email field using a regular expression.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LoginForm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { register, handleSubmit, <span class="hljs-attr">formState</span>: { errors } } = useForm();

  <span class="hljs-keyword">const</span> onSubmit = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit(onSubmit)}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> {<span class="hljs-attr">...register</span>("<span class="hljs-attr">email</span>", { <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span>, <span class="hljs-attr">pattern:</span> /^\<span class="hljs-attr">S</span>+@\<span class="hljs-attr">S</span>+$/<span class="hljs-attr">i</span> })} /&gt;</span>
      {errors.email &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Email is required and must be valid<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> {<span class="hljs-attr">...register</span>("<span class="hljs-attr">password</span>", { <span class="hljs-attr">required:</span> <span class="hljs-attr">true</span> })} /&gt;</span>
      {errors.password &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Password is required<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> LoginForm;
</code></pre>
<p><img src="https://i.imgur.com/zDd8ZDK.gif" width="900" height="450" alt="zDd8ZDK" loading="lazy"></p>
<p>In this section, we've covered the basics of how to use React Hook Form:</p>
<ul>
<li>To register form fields</li>
<li>Handle form submissions</li>
<li>Display validation errors</li>
</ul>
<p>But this is just the tip of the iceberg. React Hook Form offers many more features and capabilities that we haven't covered here. So I highly recommend that you check out the React Hook Form <a target="_blank" href="https://react-hook-form.com/get-started/">documentation</a> to learn more about how to use it effectively in your projects.</p>
<h2 id="heading-recap">Recap</h2>
<p>In this tutorial, we covered the basics of building forms in React. We learned that there are two common approaches to building forms in React: controlled and uncontrolled components.</p>
<p>Controlled components rely on state management to track the state of form inputs, while uncontrolled components use <code>refs</code> to access the form inputs and their values.</p>
<p>We also learned that using third-party libraries make form creation in React much easier. Libraries like React Hook Form provide a lot of functionality out of the box and can help reduce the amount of boilerplate code you need to build forms in React.</p>
<p>With these concepts in mind, you should be able to build complex forms in React that are easy to manage and provide a great user experience.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you want access to all the code used in this article, including the styling, I have compiled it all in a single <a target="_blank" href="https://github.com/dboatengg/react-forms">repository</a> for your convenience. Head over to the repository and you will find everything you need.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous Programming in JavaScript – Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ To understand what asynchronous programming means, think about multiple people working on a project simultaneously, each on a different task. In traditional (synchronous) programming, each person would have to wait for the person before them to finis... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-programming-in-javascript/</link>
                <guid isPermaLink="false">66bd9047abf0ccf74f1ce9a3</guid>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Tue, 31 Jan 2023 23:17:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Asynchronous-programming.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>To understand what asynchronous programming means, think about multiple people working on a project simultaneously, each on a different task.</p>
<p>In traditional (synchronous) programming, each person would have to wait for the person before them to finish their task before starting their own. </p>
<p>But with asynchronous programming, everyone can start and work on their tasks simultaneously without waiting for the others to finish.</p>
<p>Similarly, in a computer program, asynchronous programming allows a program to work on multiple tasks simultaneously instead of completing one task before moving on to the next one. This can make the program get more things done in a shorter amount of time.</p>
<p>For example, a program can send a request to a server while handling user input and processing data, all at the same time. This way, the program can run more efficiently.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-321.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this article, we will delve into the world of asynchronous programming in JavaScript, exploring the different techniques and concepts that are used to achieve this powerful programming paradigm. </p>
<p>From callbacks to promises and async/aawait, you will understand how to harness the power of asynchronous programming in your JavaScript projects.</p>
<p>Understanding asynchronous programming is essential for building high-performance web applications, whether you're a seasoned developer or just getting started with JavaScript. So, read on to learn more about this vital concept.</p>
<h2 id="heading-what-is-synchronous-programming">What is Synchronous Programming?</h2>
<p>Synchronous programming is a way for computers to do things one step at a time, in the order they are given the instructions. </p>
<p>Imagine you're cooking dinner and have a list of tasks, like boiling water for pasta, frying chicken, and making a salad.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-343.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You would do these tasks one at a time and wait for each one to finish before moving to the next. </p>
<p>Synchronous programming works similarly, where the computer will complete one task before moving on to the next. This makes it easy to understand and predict what the computer will do at any given time.</p>
<p>Here's an example of synchronous code in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define three functions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">firstTask</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 1"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">secondTask</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 2"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">thirdTask</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Task 3"</span>);  
}

<span class="hljs-comment">// Execute the functions</span>
firstTask();
secondTask();
thirdTask();
</code></pre>
<p>This code will output the following messages in the order they appear:</p>
<pre><code><span class="hljs-string">"Task 1"</span>
<span class="hljs-string">"Task 2"</span>
<span class="hljs-string">"Task 3"</span>
</code></pre><p>The code will execute the tasks in the order you see them and wait for each task to be completed before moving on to the next one.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-244.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram showing how synchronous programming works.</em></p>
<p>However, synchronous programming can be problematic in certain situations, particularly when dealing with tasks that take a significant amount of time to complete.</p>
<p>For example, let's say that a synchronous program performs a task that requires waiting for a response from a remote server. The program will be stuck waiting for the response and cannot do anything else until the response is returned. This is known as <em>blocking</em>, and it can lead to an application appearing unresponsive or "frozen" to the user.</p>
<p>Consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someLongRunningFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> start = <span class="hljs-built_in">Date</span>.now();
    <span class="hljs-keyword">while</span> (<span class="hljs-built_in">Date</span>.now() - start &lt; <span class="hljs-number">5000</span>) {
        <span class="hljs-comment">// do nothing</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello"</span>;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Starting...'</span>);

<span class="hljs-keyword">let</span> result = someLongRunningFunction();
<span class="hljs-built_in">console</span>.log(result);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'...Finishing'</span>);
</code></pre>
<p>In this example:</p>
<ul>
<li>The program starts by logging <em>"Starting..."</em> to the console.</li>
<li>Then it calls the <code>someLongRunningFunction</code>, which simulates a long-running task that takes 5 seconds to complete. This function will block the execution of the rest of the program while it runs. </li>
<li>Once the function completes, it will return <em>"Hello"</em>, and the program will log it on the console.</li>
<li>Finally, the program will log <em>"Finishing"</em> to the console.</li>
</ul>
<p>During the 5 seconds that <code>someLongRunningFunction()</code> is being executed, the program will be blocked, become unresponsive, and be unable to execute the next line of code. This can cause the program to take a long time to complete and make the application unresponsive to the user.</p>
<p>However, if the program is executed asynchronously, it will continue to run the next line of code instructions rather than becoming blocked. This will enable the program to remain responsive and execute other code instructions while waiting for the timeout to complete.</p>
<h2 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h2>
<p>Asynchronous programming is a way for a computer program to handle multiple tasks simultaneously rather than executing them one after the other. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-336.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram showing how asynchronous programming works.</em></p>
<p>Asynchronous programming allows a program to continue working on other tasks while waiting for external events, such as network requests, to occur. This approach can greatly improve the performance and responsiveness of a program.</p>
<p>For example, while a program retrieves data from a remote server, it can continue to execute other tasks such as responding to user inputs. </p>
<p>Here's an example of an asynchronous program using the <code>setTimeout</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start of script"</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First timeout completed"</span>);
}, <span class="hljs-number">2000</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"End of script"</span>);
</code></pre>
<p>In this example, the <code>setTimeout</code> method executes a function after a specified time. The function passed to <code>setTimeout</code> will be executed asynchronously, which means that the program will continue to execute the next line of code without waiting for the timeout to complete.</p>
<p>When you run the code, the output will be:</p>
<pre><code>Start <span class="hljs-keyword">of</span> script
End <span class="hljs-keyword">of</span> script
First timeout completed
</code></pre><p>As you can see, <code>console.log("First timeout completed")</code> will be executed after 2 seconds. Meanwhile, the script continues to execute the next code statement and doesn't cause any "blocking" or "freezing" behaviour.</p>
<p>In JavaScript, asynchronous programming can be achieved through a variety of techniques. One of the most common methods is the use of <em>callbacks</em>.</p>
<h2 id="heading-how-to-use-a-callback-function">How to Use a Callback Function</h2>
<p>Let's say you want to plan a birthday party for your child. You have to invite the guests, order a cake, and plan the games. But you also want to hire a clown to entertain the guests. You can only have the clown come to the party once all the other party arrangements are done, and the guests have arrived.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-341.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of a clown</em></p>
<p>So, you tell the clown to come to the party only after you have notified him that the guests have arrived. In this case, the clown represents a callback function, and the "guests arriving" represents the function that has to complete execution before the callback can be executed.</p>
<p>In code, a callback function is a function that is passed as an argument to another function, and it is executed after the first function has finished running. It's commonly used in JavaScript to handle asynchronous operations like fetching data from a server, waiting for a user's input, or handling events.</p>
<p>Here is a simple example of how you can use a callback function to handle an asynchronous operation:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Declare function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = {<span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>};
    callback(data);
  }, <span class="hljs-number">3000</span>);
}

<span class="hljs-comment">// Execute function with a callback</span>
fetchData(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-built_in">console</span>.log(data);
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Data is being fetched..."</span>);
</code></pre>
<p>In this example:</p>
<ul>
<li>We have a function called <code>fetchData</code> that uses the <code>setTimeout</code> method to simulate an asynchronous operation. The function takes a callback as an argument.</li>
<li>The callback function is then passed the data retrieved by the function after the timeout has been completed.</li>
</ul>
<p>The <code>setTimeout</code> method is used to execute the callback after a specified time (in this case, 3 seconds). The callback will be executed asynchronously, which means that the program will continue to execute the next line of code without waiting for the timeout to complete.</p>
<p>When you run the code, the output will be:</p>
<pre><code>Data is being fetched...
{<span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>}
</code></pre><p>As you can see, <code>console.log("First timeout completed")</code> will be executed after 3 seconds. Meanwhile, the script continues to execute the next statement, <code>console.log("Data is being fetched...");</code>. </p>
<p>This is the core concept of asynchronous programming. The script doesn't wait for the asynchronous operation to complete. It just continues to execute the next instruction.</p>
<h2 id="heading-what-is-callback-hell">What is Callback Hell?</h2>
<p>Callbacks provide a useful way to handle asynchronous operations. However, when many callbacks are nested, the code can be complex and hard to read and understand. </p>
<p>This happens when you chain multiple callbacks together, one after the other, creating a pyramid-like structure of indentation called callback hell, also known as the "Pyramid of Doom".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-340.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is an example of callback hell:</p>
<pre><code class="lang-javascript">getData(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a</span>) </span>{
  getMoreData(a, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">b</span>) </span>{
    getEvenMoreData(b, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">c</span>) </span>{
      getEvenEvenMoreData(c, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>) </span>{
        getFinalData(d, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">finalData</span>) </span>{
          <span class="hljs-built_in">console</span>.log(finalData);
        });
      });
    });
  });
});
</code></pre>
<p>In this example:</p>
<ol>
<li>The <code>getData</code> function takes a callback as an argument and is executed after data is retrieved.</li>
<li>The callback function then takes the data and calls the <code>getMoreData</code> function, which also takes a callback as an argument, and so on.</li>
</ol>
<p>This nesting of callbacks can make the code difficult to maintain, and the indentation makes it even harder to see the overall structure of the code.</p>
<p>To avoid callback hell, you can use a more modern way of handling async operations known as promises. Promises provide a more elegant way of handling the asynchronous flow of a program compared to callback functions. This is the focus of the next section.</p>
<h2 id="heading-how-do-promises-work">How Do Promises Work?</h2>
<p>A promise represents a way of handling asynchronous operations in a more organized way. It serves the same purpose as a callback but offers many additional capabilities and a more readable syntax.</p>
<p>A promise in JavaScript is a placeholder for a future value or action. By creating a promise, you are essentially telling the JavaScript engine to "promise" to perform a specific action and notify you once it is completed or fails.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-339.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of a promise and the JS engine</em></p>
<p>Next, callback functions are then attached to the promise to handle the outcome of the action. These callbacks will be invoked when the promise is fulfilled (action completed successfully) or rejected (action failed).</p>
<p>As a JavaScript developer, you will likely spend more time consuming promises returned by asynchronous Web APIs and managing their outcomes rather than creating them yourself. </p>
<h3 id="heading-how-to-create-a-promise">How to Create a Promise</h3>
<p>To create a promise<em>,</em> you'll create a new instance of the <code>Promise</code> object by calling the <code>Promise</code> constructor.</p>
<p>The constructor takes a single argument: a function called <code>executor</code>. The "executor" function is called immediately when the promise is created, and it takes two arguments: a <code>resolve</code> function and a <code>reject</code> function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-345.png" alt="Image" width="600" height="400" loading="lazy">
<em>Diagram of the anatomy of a promise.</em></p>
<p>Write the following line of code to declare a promise:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Initialize a promise</span>
<span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) =&gt; </span>{})
</code></pre>
<p>Now, let's inspect the <code>myPromise</code> object by logging it to the console.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(myPromise);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/promise-object.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>This image represents an output of inspecting the <code>promise</code> object.</em></p>
<p>As you can see, the promise has a <em>pending</em> status and an <em>undefined</em> value. This is because nothing has been set up for the promise object yet, so it's going to sit there in a pending state forever without any value or result.</p>
<p>Now, let's set up <code>myPromise</code> to resolve with a string printed to the console after 2 seconds.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        resolve(<span class="hljs-string">"Hello from the promise!"</span>);
    }, <span class="hljs-number">2000</span>);
});
</code></pre>
<p>Now, when you inspect <code>myPromise</code> object, you'll find that it has a status of <em>"fulfilled</em>", and a value set to the string you passed to the <code>resolve</code> function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/myPromise-obj.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A promise has three states:</p>
<ul>
<li><strong>Pending:</strong> initial state, neither fulfilled nor rejected.</li>
<li><strong>Fulfilled:</strong> meaning that an operation was completed successfully.</li>
<li><strong>Rejected:</strong> meaning that an operation failed.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-347.png" alt="Image" width="600" height="400" loading="lazy">
<em>Pending, fulfilled, and rejected states of a promise.</em></p>
<p>It's important to note that a promise is said to be settled when it is resolved or rejected.</p>
<p>Now that you know how promises are created, let's look at how you may consume them.</p>
<h3 id="heading-how-to-consume-a-promise">How to Consume a Promise</h3>
<p>Consuming a promise involves the following steps:</p>
<ol>
<li><strong>Obtain a reference to the promise:</strong> To consume a promise, you first need to obtain a reference to it. Based on the code from the previous section, our reference to a promise will be the <code>myPromise</code> object.</li>
<li><strong>Attach callbacks to the promise:</strong> Once you have a reference, you can attach callback functions by using the <code>.then</code> and <code>.catch</code> methods. The <code>.then</code> method is called when a promise is fulfilled and the <code>.catch</code> method is called when a promise is rejected.</li>
<li><strong>Wait for the promise to be fulfilled or rejected:</strong> Once you've attached callbacks to the promise, you can wait for the promise to be fulfilled or rejected.</li>
</ol>
<p>Here is an example of how you might consume a promise:</p>
<pre><code class="lang-javascript">myPromise
    .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(result);
    })
    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(error);
    });
</code></pre>
<p>Once the promise is fulfilled, the <code>.then</code> callback method will be called with the resolved value. And if the promise is rejected, the <code>.catch</code> method will be called with an error message.</p>
<p>You can also add the <code>.finally()</code> method, which will be called after a promise is settled. This means that <code>.finally()</code> will be invoked regardless of the status of a promise (whether resolved or rejected).</p>
<pre><code class="lang-javascript">myPromise
  .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(result);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(error);
  })
  .finally(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">//code here will be executed regardless of the status</span>
    <span class="hljs-comment">//of a promise (fulfilled or rejected)</span>
  });
</code></pre>
<h3 id="heading-how-to-chain-promises">How to Chain Promises</h3>
<p>Promise chaining is a pattern that allows for a clear and easy-to-understand approach to handling asynchronous operations.</p>
<p>The pattern involves connecting multiple promises in a sequence, where the output of one promise is passed as input to the next promise.</p>
<p>The linking of the promises is achieved using the <code>then()</code> method. This method uses a callback function as an argument and returns a new promise. The new promise is then resolved with the value returned by the callback function.</p>
<p>Here is an example of promise chaining:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://example.com/data'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> processData(data))
    .then(<span class="hljs-function"><span class="hljs-params">processedData</span> =&gt;</span> {
        <span class="hljs-comment">// do something with the processed data</span>
    })
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error))
</code></pre>
<p>From the above code:</p>
<ul>
<li>The first promise, which is the <code>fetch API</code> function, is fetching data from a server. </li>
<li>The second promise is parsing the response as JSON. </li>
<li>The third promise is processing the data. </li>
<li>The fourth promise is performing action on the data.</li>
<li>The <code>.catch</code> method at the end of the chain will handle any errors that occurred in any of the previous promises.</li>
</ul>
<p>It's important to keep in mind that <code>.then</code> methods are executed asynchronously and in order, each one waiting for the previous one to be resolved, and that the returned value of each <code>.then</code> will be passed as an argument to the next one.</p>
<h3 id="heading-error-handling">Error Handling</h3>
<p>When a promise is rejected, it will trigger the <code>.catch()</code> method, which handles errors. The <code>.catch()</code> method takes a single argument, which is the error thrown.</p>
<p>Another way of handling errors in a promise is by using the "try-catch" block inside a <code>.then</code> method.</p>
<p>Here is an example:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://api.github.com/users/octocat"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">//processing received data</span>
      <span class="hljs-built_in">console</span>.log(data);
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.log(error);
    }
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>From the above code:</p>
<ul>
<li>The <code>fetch()</code> function makes a request to the GitHub API to fetch user data.</li>
<li>The "try-catch" block is used inside the second <code>.then</code> method to handle any error that may occur when processing the data received from the server. </li>
<li>And the outer <code>.catch</code> method will only catch errors that occur during the fetch request.</li>
</ul>
<p>Handling errors is very important because promises are used to handle asynchronous operations, and these operations may fail for various reasons.</p>
<p>If an error occurs during the execution of a promise and it is not handled, the program will continue to execute and may lead to unexpected behaviour or crashes.</p>
<p>By handling errors, we can ensure that the program can continue to function even when an error occurs and also provide meaningful feedback to the user about the problem.</p>
<h3 id="heading-how-to-use-the-promiseall-method">How to Use the Promise.all Method</h3>
<p>The <code>Promise.all()</code> method takes an array of promises as input and returns a single promise that is fulfilled when all input promises have been fulfilled. It can be useful when you wait for multiple promises to be resolved before taking action.</p>
<p>For example, if you want to fetch data from multiple URLs.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> promise1 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/1'</span>);
<span class="hljs-keyword">let</span> promise2 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/2'</span>);
<span class="hljs-keyword">let</span> promise3 = fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/3'</span>);
</code></pre>
<p>Here, <code>promise1</code>, <code>promise2</code>, and <code>promise3</code> are promises that are fetching data from three different URLs.</p>
<p>Now, you can use <code>Promise.all([promise1, promise2, promise3])</code> to wait for all the promises to resolve before doing something with the data, as shown below.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3])
.then(<span class="hljs-function">(<span class="hljs-params">values</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(values);
})
</code></pre>
<p>In the above example:</p>
<ul>
<li><code>Promise.all()</code> takes an array of promises as input and returns a new promise. </li>
<li>The <code>then</code> method is then called on the returned promise to log the resolved values of all the input promises in the order they were passed to <code>Promise.all()</code>.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-26-103003-1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that in an instance where any input promises are rejected, the returned promise will also be rejected with the value of the first rejected promise. </p>
<h3 id="heading-how-to-use-the-fetch-api-with-promises">How to Use the Fetch API with Promises</h3>
<p>I have been using the Fetch API for some examples in this article, and I understand that it may be unfamiliar to some readers. So I created this section to explain the basics of the Fetch API for those who may need to become more familiar with it.</p>
<p>The Fetch API is a built-in JavaScript feature that allows you to make network requests, such as fetching data from a server. It is a modern alternative to the older XMLHttpRequest API and is designed to be easier and more powerful.</p>
<p>Here is an example of how to use the Fetch API to fetch data from a server:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://some-api.com/data'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
  });
</code></pre>
<p>In this example,</p>
<ul>
<li>The <code>fetch()</code> method is used to make a request to the server located at "<a target="_blank" href="https://some-api.com/data">https://some-api.com/data</a>". The returned value is a promise that will be fulfilled with the server's response.</li>
<li>The first <code>.then()</code> method is called to consume the promise and extract JSON data from the response.  </li>
<li>The next <code>then()</code> method is called to log the extracted data to the console.</li>
<li>If any errors occur, they will be caught in the <code>catch()</code> method and logged to the console.</li>
</ul>
<p>I hope the above explanation helps to clear up any confusion about the Fetch API and allows you to better understand the examples provided in this article.</p>
<h2 id="heading-async-functions-with-asyncawait"><strong>Async Functions with <code>async</code>/<code>await</code></strong></h2>
<p><code>Async/Await</code> is a feature that allows you to write asynchronous code in a more synchronous, readable way. </p>
<ul>
<li><code>async</code> is a keyword that is used to declare a function as asynchronous. </li>
<li><code>await</code> is a keyword that is used inside an <code>async</code> function to pause the execution of the function until a promise is resolved. </li>
</ul>
<p>Here's an example of how you can use <code>async/await</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/1'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(data);
}

getData();
</code></pre>
<p>In this example, </p>
<ul>
<li>the <code>getData</code> function is declared as an asynchronous function using the <code>async</code> keyword. </li>
<li>Inside the asynchronous function, we use the <code>await</code> keyword to wait for the <code>fetch</code> function to complete and retrieve some data from an API. </li>
<li>Once the data is retrieved, we use <code>await</code> again to wait and parse the retrieved data as JSON.</li>
<li>And then finally, we log the data to the console.</li>
</ul>
<p>"Aync/Await" is a powerful tool for handling asynchronous operations. It allows for more readable and maintainable code by eliminating the need for callbacks and providing a more intuitive way to handle asynchronous operations.</p>
<p>Using the "async" keyword before a function definition and the "await" keyword before an asynchronous operation makes the code look more like synchronous code, making it easier to understand.</p>
<p>Overall, "Async/Await" is valuable to the JavaScript developer's toolbox and can significantly simplify handling asynchronous operations in your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, asynchronous programming is an essential concept in JavaScript that allows your code to run in the background without blocking the execution of other code. </p>
<p>Developers can create more efficient and responsive applications by using features like callbacks, async/await, and promises.</p>
<p>Asynchronous programming can be tricky to understand at first. But with practice and a solid understanding of the concepts, it becomes a powerful tool for building high-performance web applications.</p>
<p>Thank you for reading this article!</p>
<p>If you enjoyed this article and want to learn more about programming, follow me on Instagram at <a target="_blank" href="https://www.instagram.com/alege_dev/">@alege_dev</a>, where I post regular updates and tips on various programming topics. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How the Document Object Model Works in JavaScript – DOM Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The Document Object Model (DOM) is an essential part of web development. It provides a way for programmers to interact with and manipulate the structure of a website.  With the help of the DOM, developers can access and change the different parts of ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-dom/</link>
                <guid isPermaLink="false">66bd90522384aa6dc0878d5f</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Thu, 19 Jan 2023 15:21:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/JavaScript-DOM-cover-image1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Document Object Model (DOM) is an essential part of web development. It provides a way for programmers to interact with and manipulate the structure of a website. </p>
<p>With the help of the DOM, developers can access and change the different parts of a webpage. This allows them to create dynamic and interactive websites, where user interactions can trigger changes in the page's layout and content. </p>
<p>Understanding the DOM is crucial for creating responsive and user-friendly websites. So in this article, we will delve deeper into what the DOM can do and how you can use it in JavaScript.</p>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>The DOM, or Document Object Model, is like a map of a website. Just like how a map shows you where all the streets and buildings are in a city, the DOM shows you where everything is on a website. </p>
<p>The DOM helps your computer understand the different parts of a website and how they are put together. </p>
<p>Just like you can use a map to find your way around a city, programmers can use the DOM to find different parts of a website and change their properties. For example, they can make a button change color when a user hovers over it or make pictures move around on the screen.</p>
<p>The DOM is like a big puzzle. But using JavaScript, we can move the puzzle pieces around and make a website look and work however we want it to work.</p>
<h2 id="heading-the-dom-javascript">The DOM + JavaScript</h2>
<p>JavaScript is a programming language that helps us interact with the DOM. The DOM and JavaScript are like two friends that work together to make websites cool and interactive. Again, the DOM is like a big map that shows where all the different parts of the website are located.</p>
<p>On the other hand, JavaScript is like a magic wand that can change a website by using the map (DOM) to find the different parts of the website. It can make a button change color when you click on it or make a picture move to a different spot on the page. </p>
<p>Together, the DOM and JavaScript make the website come alive and respond to what you do, like moving your mouse or clicking on a button. </p>
<p>In summary, the DOM is like a map that shows where everything is and JavaScript is like a magic wand that can change things on that map.</p>
<h2 id="heading-dom-structure-understanding-the-dom-tree">DOM Structure – Understanding the DOM Tree</h2>
<p>Imagine a website is like a big book, and each page in that book represents a different part of the website. The DOM tree is like a table of contents for that book. It shows you all the different parts of the website, and how they are organized. </p>
<p>Each part of the website is called an "element" and these elements are arranged in a tree-like structure. </p>
<p>The top of the tree is called the "root" and it represents the entire website. From there, the tree branches out into different sections, like the headings, paragraphs, images, and others that make up the entire website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/DOM-tree-5.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of the DOM tree</em></p>
<p>Just like how the table of contents in a book helps you find specific pages, the DOM tree helps computers find specific elements on a website. In addition, it allows developers to access and change those elements, so they can make the website interactive. </p>
<p>In short, the DOM tree represents the structure of a website in a way that computers can understand. Developers can use it to access and manipulate different elements in that structure to create dynamic web pages.</p>
<h2 id="heading-how-to-access-the-dom">How to Access the DOM</h2>
<p>Accessing elements in the DOM means finding specific parts of a website and changing or manipulating them. </p>
<p>To access an element on a website, you need to know the specific element you want to access. </p>
<p>JavaScript provides different methods to access the elements in the DOM, such as <code>getElementById</code>, <code>getElementsByTagName</code>, <code>querySelector</code>, and <code>querySelectorAll</code>. </p>
<p>These methods allow you to find an element based on its <code>id</code>, <code>tagname</code>, or <code>classname</code> and select it for manipulation. </p>
<p>For example, you can access a button on a webpage and change its text or color when a user clicks on it. Or, you can access an image on a webpage and change it to a different image when a user hovers over it. </p>
<p>Here's an example of how you might use the DOM to access an element on a webpage: </p>
<p>Let's say you have a webpage that displays a list of students and you want to change the background color of a specific student when they are clicked. </p>
<p>You can use the DOM method <code>getElementById</code> to access the specific element that represents the student and then use the <code>style</code> property in JavaScript to change the background color of that element.</p>
<p>Here's how that might look:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-list"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"student"</span>&gt;</span>John<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-2"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"student"</span>&gt;</span>Alice<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-3"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"student"</span>&gt;</span>Bob<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.student</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
}
<span class="hljs-selector-class">.student</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f1f1f1</span>;
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> student1 = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"student-1"</span>);

student1.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  student1.style.backgroundColor = <span class="hljs-string">"lightblue"</span>;
});
</code></pre>
<p>In this example, JavaScript is using the <code>getElementById</code> method to select the element with the id "student-1" and it changes its <code>backgroundColor</code> property to "light blue" when you click on it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Document_4.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Similarly, you can use <code>getElementsByClassName</code> to select all elements with a specific class and <code>querySelector</code> to select an element based on a CSS selector.</p>
<p>This is just a basic example, but it illustrates how you can use the DOM to access specific elements on a webpage and change their properties in response to user interaction.</p>
<h2 id="heading-how-to-add-remove-and-modify-dom-elements">How to Add, Remove, and Modify DOM Elements</h2>
<p>Adding, removing, and modifying elements in the DOM refers to adding new elements to a webpage, removing existing elements, and changing the properties of existing elements.</p>
<p>For example, if you want to add a new button to a webpage, you would use JavaScript to create a new element and then use the DOM to add that element to the webpage. Similarly, if you want to remove an element, you would use the DOM to find the element and then delete it.</p>
<p>Modifying elements also involves making changes to the properties of an existing element. For example, you could use the DOM to change the text inside a button.</p>
<p>Here’s how you can express this in code.:</p>
<pre><code class="lang-html">    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"wrapper"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-wrapper"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"create-btn"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Create new button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.btn-wrapper</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> createButton = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"create-btn"</span>);
<span class="hljs-keyword">let</span> wrapper = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"wrapper"</span>);

createButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> newButton = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"button"</span>);
  newButton.innerHTML = <span class="hljs-string">"Click me"</span>;
  wrapper.appendChild(newButton);
});
</code></pre>
<p>In the above example, we are creating a new button element and setting the text inside the button to "Click me". Then we're using the <code>appendChild</code> method to add this new button element to the webpage.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Document.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-recap">Recap</h2>
<p>The Document Object Model (DOM) is an essential tool for creating interactive, dynamic web pages using JavaScript. It allows developers to access and manipulate the contents of a webpage in real time. </p>
<p>Understanding the DOM tree and how to access, add, remove, and modify elements is crucial for JavaScript developers.</p>
<p>We've seen how the DOM represents a webpage as a tree of objects and how we can use different methods like <code>getElementById</code>, <code>getElementsByTagName</code>, <code>querySelector</code>, and <code>querySelectorAll</code> to access specific elements on a webpage. With these methods, we can change the content, style, or layout of a webpage after it has loaded in the browser. </p>
<p>Additionally, we've seen how to add new elements to a webpage, remove existing elements, and change the properties of existing elements.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this article has given you a better understanding of the Document Object Model and how to use it to create dynamic web pages. </p>
<p>Remember that the DOM is a powerful tool that you can use to create amazing websites, so don't be afraid to experiment and try new things.</p>
<p>Thanks for reading! Kindly share this article and follow me on  Twitter <a target="_blank" href="https://twitter.com/alege_dev">@alege_dev</a> for updates on future posts.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
