<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>Sidali Assoul</title><description>Full Stack Engineer specializing in scalable SaaS platforms and AI microservices. NestJS, Next.js, TypeScript, Laravel.</description><link>https://sidaliassoul.com/</link><language>en-us</language><item><title>Master Python Asyncio: A Comprehensive Guide </title><link>https://sidaliassoul.com/blog/master-python-asyncio-comprehensive-guide/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/master-python-asyncio-comprehensive-guide/</guid><description>Master Python asyncio: learn coroutines, async/await, the event loop, Tasks, asyncio.gather, TaskGroups (Python 3.11+), and Futures for non-blocking I/O.</description><pubDate>Mon, 20 Apr 2026 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;If you are not leveraging asynchronous programming, your program is likely wasting most of its time waiting for external I/O-bound operations like network requests or database calls rather than actually processing data or handling user requirements.&lt;/p&gt;
&lt;p&gt;In other words, your program is literally wasting time doing nothing rather than switching to another task. Asynchronous programming solves this problem by ensuring the program isn&apos;t blocked by I/O-bound tasks, allowing it to switch to other operations instead of staying idle.&lt;/p&gt;
&lt;p&gt;In this guide, we will break down how to implement this effectively in your Python projects. By the end of this tutorial, you&apos;ll understand:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;What &quot;asynchronous&quot; actually means&lt;/strong&gt; and why it is the key to handling waiting I/O tasks.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to choose&lt;/strong&gt; between &lt;code&gt;asyncio&lt;/code&gt;, threads, and subprocesses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The fundamentals of coroutines&lt;/strong&gt;, including writing your first async code, identifying the &quot;sequential async trap,&quot; and understanding how the event loop runs tasks concurrently.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;How to use Tasks&lt;/strong&gt;, an abstraction above coroutines that allows us to schedule and manage concurrent execution.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Future&lt;/strong&gt;, the third type of awaitable in Python, and how it represents an eventual result.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So without any further ado let&apos;s dive in.&lt;/p&gt;
&lt;h2&gt;Mastering Asynchronous I/O: How to Handle Waiting Tasks&lt;/h2&gt;
&lt;p&gt;So what does async even mean? And how exactly does it  help in handling I/O-bound computations?&lt;/p&gt;
&lt;p&gt;Whatever the programming language, the framework, or the environment, when you hear about async, you should instantly think about I/O-bound tasks.&lt;/p&gt;
&lt;p&gt;And by IO-bound tasks I mean literally any computing task where our process/program spends most of its time waiting for data. Think of:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reading a file from disk.&lt;/li&gt;
&lt;li&gt;Fetching data in the network via API calls...&lt;/li&gt;
&lt;li&gt;User interaction: Waiting for a user to type something on the keyboard or to click on a button.&lt;/li&gt;
&lt;li&gt;And so on.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let&apos;s say you just woke up, prepared a cup of coffee, turned on your machine, and started typing on your keyboard, chuckling and sipping coffee with every keystroke.&lt;/p&gt;
&lt;p&gt;You soon find out, however, that your task has a dependency on a teammate. In other words, you cannot proceed until your coworker finishes their task first.&lt;/p&gt;
&lt;p&gt;&quot;Okay, good, let&apos;s just take a walk in nature until John finishes the task. I&apos;m blocked, after all; I can&apos;t do anything.&lt;strong&gt;&quot;&lt;/strong&gt; That&apos;s what a synchronous program would have said.&lt;/p&gt;
&lt;p&gt;But you aren&apos;t one. Instead of waiting for your coworker (a.k.a. the external I/O-bound task) to finish their work, you can just proceed asynchronously by switching to another task until they are done.&lt;/p&gt;
&lt;p&gt;The same analogy can be applied to our program. If a part of the program is waiting for a record to be written to the database or a file to be saved to the disk, it should not stay idle. Instead, it can leverage that time to switch to other asynchronous tasks, such as fetching data from external APIs.&lt;/p&gt;
&lt;p&gt;As you can see, async is not about executing tasks in parallel. It is all about avoiding doing nothing while our program stays idle waiting for an external I/O-bound operation to be completed. It’s about leveraging that wasted time to execute other operations.&lt;/p&gt;
&lt;h2&gt;How to Choose between Asyncio, Threads and Subprocesses&lt;/h2&gt;
&lt;p&gt;In software engineering, there is no silver bullet that works for everything and in all cases. That&apos;s why we need to make sure that we are employing the right solution for the right use case.&lt;/p&gt;
&lt;p&gt;Asyncio, threads and multiprocessing three common ways to speed up a program. Here&apos;s what each one mean and where it exactly shines.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Asyncio&lt;/strong&gt;: As we previously stated, whenever you hear the word &quot;async,&quot; think about I/O-bound tasks. If you think that your program will deal with a lot of external systems such as databases, file system operations, or network requests, then asyncio is your best choice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Threads&lt;/strong&gt;: Use them for parallel (concurrent if GIL enabled) tasks that share data with minimal CPU use.&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;Threads are not really parallel in Python because of the Global Interpreter Lock (GIL). Which is a mutex ensuring that only one thread is executing python bytecode at a time&lt;/li&gt;
&lt;li&gt;In the latest version of Python, they introduced a free-threaded build, but it&apos;s not enabled by default for compatibility reasons.&lt;/li&gt;
&lt;/ul&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Multiprocessing&lt;/strong&gt;: Unlike threads, each process has its own instance of the Python interpreter. This means you can truly utilize 100% of your multi-core processor.&lt;/li&gt;
&lt;/ol&gt;
&lt;ul&gt;
&lt;li&gt;Subprocesses cost more memory as each one has its own memory and instance of the Python interpreter.&lt;/li&gt;
&lt;li&gt;But speed and isolation pays for that cost here; a crash in one subprocess won&apos;t affect the others.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Your First Async Code&lt;/h2&gt;
&lt;h3&gt;Getting Started&lt;/h3&gt;
&lt;p&gt;Now that we understand the importance of asynchronous operations, let&apos;s write our first async code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;async def main():
    print(&quot;Start of main coroutine&quot;)

main()

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To declare an async function, we use the built-in async keyword; adding async in front of a function transforms it into an async function or what&apos;s called a &lt;strong&gt;coroutine.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Trying to run the code above will result in printing the following runtime warning:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;RuntimeWarning: coroutine &apos;main&apos; was never awaited
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can notice as well that the main function&apos;s code never executes as well. Nothing gets printed except the warning.&lt;/p&gt;
&lt;p&gt;Hmm, interesting. Let&apos;s try to print what&apos;s returned by the async main function&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
async def main():
    print(&quot;Start of main coroutine&quot;)

print(main()) # --&amp;gt; &amp;lt;coroutine object main at 0x10711bf40&amp;gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can observe that the async function &lt;code&gt;main&lt;/code&gt; returned a &lt;strong&gt;coroutine object&lt;/strong&gt;. From this, we can conclude that when a function is defined with the &lt;code&gt;async&lt;/code&gt; keyword, calling it does not execute the code immediately; instead, it returns a &lt;strong&gt;coroutine object&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;But wait, what&apos;s a coroutine object? And how can we &lt;strong&gt;&quot;await for it&quot;&lt;/strong&gt; to avoid the previous warning?&lt;/p&gt;
&lt;p&gt;A coroutine object is one of the three awaitable objects in Python: coroutines, tasks, and futures. To await it, we need to import asyncio and wrap the main coroutine call with its &lt;code&gt;run&lt;/code&gt; method.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&quot;asyncio&quot; is a built-in Python library, so there is no need to install anything.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;import asyncio
async def main():
  print(&quot;Start of main coroutine&quot;)

asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We usually only use the run method at the top level of our code because it does two things: start the async event loop and await the passed coroutine &quot;main.&quot;&lt;/p&gt;
&lt;h3&gt;Awaiting Sequentially: When Async Acts Like Sync&lt;/h3&gt;
&lt;p&gt;Let&apos;s declare another coroutine called &lt;code&gt;fetch&lt;/code&gt;, which simulates an I/O-bound task. It stops execution for 2 seconds using the &lt;code&gt;asyncio.sleep&lt;/code&gt; method and returns a &lt;strong&gt;200&lt;/strong&gt; success code.&lt;/p&gt;
&lt;p&gt;As we can&apos;t call the fetch coroutine without awaiting it, we need to use the await built-in keyword, which can only be used inside async functions.&lt;/p&gt;
&lt;p&gt;So in the main coroutine, await the fetch call and get its result, then print it.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
import asyncio
async def fetch():
   await asyncio.sleep(2) # 2 seconds delay, simulates I/O operation.
   return 200

async def main():

  print(&quot;Start of main coroutine&quot;)
  result = await fetch()
  print(&quot;result: {result}&quot;)
  
asyncio.run(main())


&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
Start of main coroutine
result: 200

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The main coroutine prints first, the program pauses for 2 seconds, and then the fetch function executes.&lt;/p&gt;
&lt;p&gt;Let&apos;s now try to call the fetch coroutine three times in main, retrieve the result of each call, and then print them all.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
import asyncio
import time

async def fetch():
   await asyncio.sleep(2)
   return 200


async def main():
 
  start_time = time.perf_counter()
  
  print(&quot;Start of main coroutine&quot;)

  start_time = time.perf_counter()
  result1 = await fetch()
  result2 = await fetch()
  result3 = await fetch()
  end_time = time.perf_counter()
  duration = end_time - start_time
  print(f&quot;The time took {duration} to execute&quot;)

  print(f&quot;results: {[result1,result2,result3]}&quot;)
  
asyncio.run(main())


&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Start of main coroutine
The time took 6.003185832989402 to execute
results: [200,200,200]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is no performance gain here yet. The fetches are executing one after another. We are essentially waiting for each I/O task to finish before starting the next one, which defeats the purpose of being asynchronous.&lt;/p&gt;
&lt;p&gt;In other words, we are not taking advantage of our event loop here.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Sequential (await one by one) — 6 seconds total:

  fetch 1:  |████████████|
  fetch 2:              |████████████|
  fetch 3:                          |████████████|
            0s           2s          4s           6s

With Tasks (concurrent) — 2 seconds total:

  task 1:   |████████████|
  task 2:   |████████████|
  task 3:   |████████████|
            0s           2s
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;What is the event loop?&lt;/h3&gt;
&lt;p&gt;Asynchronous execution of our program allows us to leverage the wasted waiting time of I/O-bound operations by switching from one blocked task to another until all tasks are executed. But how is that achieved in practice by asyncio?&lt;/p&gt;
&lt;p&gt;That&apos;s where the Event Loop comes in.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;asyncio.run&lt;/code&gt; method creates what&apos;s called an event loop.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can think of the event loop as the orchestrator that tracks all the async coroutines. And Here&apos;s how it works in practice:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Execution Start&lt;/strong&gt;: When you call &quot;&lt;strong&gt;asyncio.run(main()),&quot;&lt;/strong&gt; the event loop starts and maintains a list of all the tasks that need to be executed. At any given moment, the loop is running exactly one task.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Yield Point:&lt;/strong&gt; The loop executes a task until it hits an &lt;strong&gt;&quot;await,&quot;&lt;/strong&gt; which is a signal that means that the task is waiting for an external I/O operation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Switch &amp;amp; Resume:&lt;/strong&gt; Instead of waiting, the loop immediately switches to another ready task. It keeps track of the &quot;waiting&quot; tasks in the background and resumes them exactly where they left off the moment their I/O operation is finished.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt; time ─────────────────────────────────────────────►

 Task 1  [runs]──► await ···················► [resume]──► done
                     │                             ▲
                     ▼                             │
 Task 2           [runs]──► await ············► [resume]──► done
                               │                    ▲
                               ▼                    │
 Task 3                     [runs]──► await ·····► [resume]──► done

         ◄──────────────── ~2 seconds ─────────────►
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Scheduling Coroutines: An Introduction to Tasks&lt;/h2&gt;
&lt;h3&gt;Creating Tasks manually&lt;/h3&gt;
&lt;p&gt;By default, asyncio does not schedule coroutines in the event loop; we need to wrap each coroutine object in a &lt;strong&gt;Task&lt;/strong&gt;. Once wrapped, the event loop manages its execution immediately, allowing the program to switch between tasks while waiting for I/O operations.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  fetch()                       asyncio.create_task(fetch())
     │                                     │
     ▼                                     ▼
┌──────────────┐               ┌─────────────────────┐
│  coroutine   │               │        Task         │
│   object     │ ──wraps────►  │    (scheduled ✓)    │
│              │               │                     │
│  idle, not   │               │  event loop will    │
│  running ✗   │               │  pick this up       │
└──────────────┘               └─────────────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s wrap the &lt;code&gt;fetch&lt;/code&gt; calls from the previous example into tasks and execute the code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;async def main():
 
  start_time = time.perf_counter()
  
  print(&quot;Start of main coroutine&quot;)

  start_time = time.perf_counter()
  task1 = asyncio.create_task(fetch())
  task2 = asyncio.create_task(fetch())
  task3 = asyncio.create_task(fetch())
  result1 = await task1
  result2 = await task2
  result3 = await task3
  end_time = time.perf_counter()
  duration = end_time - start_time
  print(f&quot;The time took {duration} to execute&quot;)

  print(f&quot;results: {[result1,result2,result3]}&quot;)
  
asyncio.run(main())
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Start of main coroutine
The time took 2.001712833996862 to execute
results: [200, 200, 200]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This time, the total execution is only 2 seconds, which matches the duration of the longest-running I/O task.&lt;/p&gt;
&lt;p&gt;Since all three tasks are waiting for a sleep I/O operation to complete, the event loop starts with the first one. Once it encounters the &lt;strong&gt;await&lt;/strong&gt; sleep call, it context switches to the second task. It continues this pattern, pausing each task at its respective &lt;strong&gt;await&lt;/strong&gt; point. These I/O operations then progress concurrently in the background, completing the entire batch in just 2 seconds.&lt;/p&gt;
&lt;h3&gt;The Gather method&lt;/h3&gt;
&lt;p&gt;Creating tasks manually for each coroutine can be cumbersome sometimes; that&apos;s why the &lt;strong&gt;&quot;asyncio.gather&quot;&lt;/strong&gt; method exists.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;&quot;gather&quot;&lt;/strong&gt; method accepts any number of coroutine objects or &lt;strong&gt;&quot;future types&quot;&lt;/strong&gt; and returns what&apos;s known as an &lt;strong&gt;&quot;asyncio.Future&quot;&lt;/strong&gt; type, which is one of the three awaitable types in Python.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;More about asyncio.Future later.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;async def main():
 
  start_time = time.perf_counter()
  
  print(&quot;Start of main coroutine&quot;)

  start_time = time.perf_counter()
  results = await asyncio.gather(fetch(),fetch(),fetch())
  end_time = time.perf_counter()
  duration = end_time - start_time
  print(f&quot;The time took {duration} to execute&quot;)

  print(f&quot;results: {results}&quot;)

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Start of main coroutine
The time took 2.0019387080101296 to execute
results: [200, 200, 200]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Just like before, the execution only takes 2 seconds. This proves that the three &quot;&lt;strong&gt;fetch&quot;&lt;/strong&gt; calls ran concurrently, rather than being blocked by sequential I/O waiting.&lt;/p&gt;
&lt;p&gt;By default, &lt;code&gt;asyncio.gather&lt;/code&gt; does not stop other tasks if one fails. Even if an exception is raised in one of the tasks, the remaining ones continue running in the background.&lt;/p&gt;
&lt;p&gt;To handle these errors gracefully without crashing, you can set &lt;code&gt;return_exceptions=True&lt;/code&gt; to treat exceptions as returned values instead of raised errors. You can then iterate through the results and handle both the exceptions and the successfully returned results as needed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import asyncio

async def fetch_success():
    await asyncio.sleep(1)
    return 200

async def fetch_fail():
    await asyncio.sleep(1)
    raise ValueError(500)

async def main():
    # With return_exceptions=True, the program won&apos;t crash
    results = await asyncio.gather(
        fetch_success(), 
        fetch_fail(), 
        return_exceptions=True
    )
    
    for res in results:
        if isinstance(res, Exception):
            print(f&quot;Task failed with: {res}&quot;)
        else:
            print(f&quot;Task succeeded with: {res}&quot;)

asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Task succeeded with: Success!
Task failed with: 500 (Internal Server Error)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When using &lt;code&gt;**gather&lt;/code&gt;,** returning exceptions as values instead of raising them makes error handling much easier. As you can see from the logs, &lt;strong&gt;Gather&lt;/strong&gt; did not stop the first task even though the second one failed.&lt;/p&gt;
&lt;h3&gt;Task Group&lt;/h3&gt;
&lt;p&gt;In Python 3.11, &lt;strong&gt;TaskGroups&lt;/strong&gt; were introduced as a safer and more structured way to manage multiple tasks.&lt;/p&gt;
&lt;p&gt;The biggest advantage of &lt;strong&gt;TaskGroup&lt;/strong&gt; is what&apos;s known as structured concurrency. In other words, if one task in the group fails, the &quot;&lt;strong&gt;TaskGroup&quot;&lt;/strong&gt; automatically cancels all the other ones.&lt;/p&gt;
&lt;p&gt;This prevents uncanceled tasks, or &lt;strong&gt;&quot;zombie tasks,&quot;&lt;/strong&gt; from wasting resources when running in the background.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;async def main():
  tasks = set()
 
  start_time = time.perf_counter()
  
  print(&quot;Start of main coroutine&quot;)

  start_time = time.perf_counter()
# The context manager ensures all tasks finish before exiting the block
  async with asyncio.TaskGroup() as tg:
      for _ in range(3):
          task = tg.create_task(fetch())
          tasks.add(task)

  end_time = time.perf_counter()
  duration = end_time - start_time
  
  # At this point, TaskGroup guarantees that all tasks have     completed successfully.
  results = [ task.result() for task in tasks]

  print(f&quot;The time took {duration} to execute&quot;)

  print(f&quot;results: {results}&quot;)
  
asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Start of main coroutine
The time took 2.001078375033103 to execute
results: [200, 200, 200]
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Note that we are tracking the running tasks in a &lt;code&gt;tasks&lt;/code&gt; set. This is done on purpose to prevent the garbage collector from cleaning up our tasks mid-execution.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The &quot;&lt;strong&gt;async with&quot;&lt;/strong&gt; block is a Python feature known as an &quot;&lt;strong&gt;async context manager.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;It acts as a barrier. The program will not proceed to the &lt;code&gt;results = ...&lt;/code&gt; line of code until every task created within that group has either finished successfully or raised an exception if one of them fails.&lt;/p&gt;
&lt;p&gt;This replaces the boilerplate code you would otherwise have to write manually to manage task lifecycles when using &lt;code&gt;asyncio.gather&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Bonus Information About Task Group&lt;/h3&gt;
&lt;p&gt;If multiple tasks fail inside a group, Python does not throw one error, but it throws an &quot;&lt;strong&gt;ExceptionGroup.&quot;&lt;/strong&gt; You can handle it using the except* syntax.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import asyncio

async def fail_fetch():
  asyncio.sleep(1) # simulate I/O-bound task
  raise ValueError(500)

async def main():
  try:
    async with asyncio.TaskGroup() as tg:
        tg.create_task(fail_fetch())
        tg.create_task(fail_fetch())
  except* ValueError as eg:
    for e in eg.exceptions:
        print(f&quot;Caught a value error: {e}&quot;)

asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Caught a value error: 500
Caught a value error: 500
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Future&lt;/h2&gt;
&lt;p&gt;Now that we have covered coroutines and tasks, let’s look at the third type of awaitable: the &lt;strong&gt;Future&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;While you rarely use these at the application level, they are essential low-level objects representing a result that hasn&apos;t arrived yet. Think of a Future as a &quot;promise&quot; or a placeholder for a value that will be set later.&lt;/p&gt;
&lt;p&gt;A Future is often used to bridge the gap between &lt;strong&gt;low-level, callback-based code&lt;/strong&gt; and modern &lt;code&gt;async/await&lt;/code&gt; syntax. When you &lt;code&gt;await&lt;/code&gt; a future, your code pauses until a value is manually pushed into it, even if the background work that pushed the value continues to run.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  loop.create_future()
          │
          ▼
  ┌──────────────┐    future.set_result(2026)    ┌──────────────────┐
  │   PENDING    │ ───────────────────────────►  │ RESOLVED: 2026   │
  └──────────────┘                               └──────────────────┘
          │                                               │
     await future                                   await future
    (suspends here,                              (returns 2026 instantly,
     yields to loop)                              loop moves on)
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;
import asyncio
import time

async def provide_data(future, value):
    await asyncio.sleep(2)
    # The Future is fulfilled here
    future.set_result(value)
    
    print(&quot;Future result set! Doing some background cleanup now...&quot;)
    await asyncio.sleep(5) 

async def main():
    start_time = time.perf_counter()

    loop = asyncio.get_running_loop()
    future = loop.create_future()
    
    # Schedule the provider
    asyncio.create_task(provide_data(future, 2026))
    
    # We wait specifically for the result, not the whole task
    result = await future
    print(f&quot;Received the future&apos;s result: {result}&quot;)
    end_time = time.perf_counter()
    duration = end_time - start_time
    print(f&quot;The program is executed in {duration} seconds&quot;)

asyncio.run(main())

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above example, we are doing the following:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Retrieving the current running event loop and creating a new future object that belongs to it.&lt;/li&gt;
&lt;li&gt;We pass the future object along with a value to a provide data coroutine, and then we wrap it inside a task to schedule it in the event loop.&lt;/li&gt;
&lt;li&gt;We won&apos;t await the task itself, but just the future object that we created.&lt;/li&gt;
&lt;li&gt;Inside the data_provider coroutine we pause the execution for 2 seconds using the sleep asyncio method, we set the future result and then we pause the execution again for 5 seconds.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Future result set! Doing some background cleanup now...
Received the future&apos;s result: 2026
The program is executed in 2.0018573330016807 seconds

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can notice that the program took only 2 seconds to execute, it didn&apos;t pause for 7 whole second waiting for the whole task to execute, as we just awaited for the future value itself not the whole task&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;So that&apos;s basically all you need to get started with asynchronous programming in Python. We covered coroutines, tasks, future, how the event loop is leveraged to manage and orchestrate concurrent running async jobs with all the necessary nitty-gritty details that you need to get you started.&lt;/p&gt;
&lt;p&gt;Despite covering all of that, there is an important thing that we didn&apos;t mention yet.&lt;/p&gt;
&lt;p&gt;As your application grows and the number of concurrent jobs increases, you may encounter race conditions because they all share the same process memory space.&lt;/p&gt;
&lt;p&gt;Race conditions occur when multiple asynchronous tasks attempt to access the same variable simultaneously. Consider a &quot;balance&quot; variable accessed by concurrent &lt;strong&gt;debit&lt;/strong&gt; and &lt;strong&gt;credit&lt;/strong&gt; functions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The &lt;strong&gt;credit&lt;/strong&gt; function reads the balance as 100.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;debit&lt;/strong&gt; function reads the balance as 100.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;credit&lt;/strong&gt; function adds 10, updating the balance to 110.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;debit&lt;/strong&gt; function subtracts 10 from the original value it read (100), updating the balance to 90.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;credit function -&amp;gt; balance: 100, newBalance: 110
debit function  -&amp;gt; balance: 100, newBalance: 90 (Overwrites the credit function&apos;s modification!)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As illustrated, the debit function overwrote the credit function&apos;s update. This is a classic example of a race condition that leads to &lt;strong&gt;data corruption&lt;/strong&gt;. However, race conditions can be even more severe; certain categories can lead to memory errors that cause the entire &lt;strong&gt;process to crash&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Race conditions are typically handled using semaphores and mutexes. In the next article, we will explore &lt;strong&gt;asyncio&lt;/strong&gt; synchronization primitives, including Locks, Semaphores, BoundedSemaphores, Events, Conditions, and Barriers.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/master-python-asyncio-comprehensive-guide.png" medium="image" type="image/png"/><category>python</category><category>tutorial</category><category>programming</category><enclosure url="https://sidaliassoul.com/open-graph/blog/master-python-asyncio-comprehensive-guide.png" length="0" type="image/png"/></item><item><title>React State Snapshots Explained: Why State Values Don&apos;t Change During Renders</title><link>https://sidaliassoul.com/blog/react-state-snapshots-explained/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-state-snapshots-explained/</guid><description>Understand how React state snapshots work and why state values remain constant within a single render, with practical examples and explanations.</description><pubDate>Wed, 09 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;pre&gt;&lt;code&gt;
function App(){
  const [counter,seCounter] =useState(1)
return (
  &amp;lt;div&amp;gt;
    &amp;lt;p&amp;gt;{counter}&amp;lt;/p&amp;gt;
    &amp;lt;button onClick={()=&amp;gt;{

      setCounter(counter + 1); 
      setTimeout(() =&amp;gt; { 
    console.log(counter);
      }, 5000);

    }}&amp;gt;&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You may get shocked to know that this code, &lt;strong&gt;will not print 2&lt;/strong&gt; 😮.&lt;/p&gt;
&lt;p&gt;Despite &lt;strong&gt;incrementing the counter by 1&lt;/strong&gt;, and then &lt;strong&gt;deferring the execution of the console log by 5 seconds using the &lt;code&gt;setTimeout&lt;/code&gt; browser &lt;code&gt;API&lt;/code&gt;&lt;/strong&gt;,which means that by the time the &lt;code&gt;console.log&lt;/code&gt; is executed the &lt;strong&gt;state will have been already incremented by 1&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;But&lt;/strong&gt; reality shows nothing but that, in fact, a 1 gets printed 🤯.&lt;/p&gt;
&lt;p&gt;In this article, we will be clarifying what&apos;s exactly happening here under the scene while explaining the concept of a &lt;strong&gt;state snapshot in &lt;code&gt;React&lt;/code&gt;&lt;/strong&gt;. So without any further ado let&apos;s get started.&lt;/p&gt;
&lt;p&gt;As you might know, &lt;code&gt;State&lt;/code&gt; doesn&apos;t live inside the function component but it&apos;s stored within the &lt;code&gt;React&lt;/code&gt; package itself!.&lt;/p&gt;
&lt;p&gt;And &lt;strong&gt;provided as a snapshot&lt;/strong&gt; or in other terms, as &lt;strong&gt;a copy of the original state&lt;/strong&gt; via the &lt;code&gt;useState&lt;/code&gt; hook.&lt;/p&gt;
&lt;p&gt;In fact, &lt;code&gt;useState&lt;/code&gt; is named a hook because **it&apos;s hooking into the external state stored in &lt;code&gt;React&lt;/code&gt; itself 🤯! **&lt;/p&gt;
&lt;p&gt;Components re-renders can be triggered via a state updates. Therefore when a given component re-renders or &lt;code&gt;gets called by React&lt;/code&gt; a new snapshot mirroring the latest updated state value is given to it, and then based on that value the whole &lt;code&gt;JSX&lt;/code&gt; including the &lt;strong&gt;attached event handlers&lt;/strong&gt; gets re-created again.&lt;/p&gt;
&lt;p&gt;So the &lt;strong&gt;deferred &lt;code&gt;console.log&lt;/code&gt;&lt;/strong&gt; in the previous code &lt;strong&gt;was printing 1&lt;/strong&gt;, because it &lt;strong&gt;was referencing the state snapshot of the first render&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;By the time the second render happens, the whole &lt;code&gt;JSX&lt;/code&gt; including its corresponding &lt;strong&gt;attached event handlers&lt;/strong&gt; will be re-created again with the &lt;strong&gt;new &lt;code&gt;counter&lt;/code&gt; state value which will be equal to 2&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Therefore, &lt;strong&gt;Every render is associated with&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A state snapshot&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;And a &lt;strong&gt;&lt;code&gt;JSX&lt;/code&gt; code including event handlers.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Similarly, If you re-tried to re-click on the &lt;code&gt;button&lt;/code&gt; again &lt;strong&gt;the &lt;code&gt;counter&lt;/code&gt; state will be incremented to 3&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Then the component will &lt;strong&gt;re-render displaying 3 on the &lt;code&gt;UI&lt;/code&gt;&lt;/strong&gt;. After 5 seconds are elapsed 2 will be printed, because as we said previously the event handler was attached to the previous render hence the &lt;strong&gt;callback function&lt;/strong&gt; is referencing the &lt;strong&gt;old state snapshot&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In other words, we can briefly say that:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The state that is returned by the &lt;code&gt;useState&lt;/code&gt; hook is constant during every render,&lt;/strong&gt; even if the event handler that is attached to one of the returned &lt;code&gt;JSX&lt;/code&gt; elements was executing asynchronously, in the future when many potential renders may have already occurred.&lt;/p&gt;
&lt;p&gt;Every render is allocated its own constant &lt;code&gt;state&lt;/code&gt; snapshot, that never change before the next render.&lt;/p&gt;
&lt;p&gt;All the derived &lt;code&gt;JSX&lt;/code&gt; code including &lt;strong&gt;event listeners&lt;/strong&gt; is tied to that specific render.&lt;/p&gt;
&lt;p&gt;In more specific words, &lt;strong&gt;renders are totally isolated&lt;/strong&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Render 1 can never access state snapshots in render 2.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;To sum up, you can think of a &lt;strong&gt;re-render&lt;/strong&gt; as a component starting a brand &lt;strong&gt;new life&lt;/strong&gt; with a brand &lt;strong&gt;new state snapshot&lt;/strong&gt;, &lt;strong&gt;&lt;code&gt;JSX&lt;/code&gt; code&lt;/strong&gt; and &lt;strong&gt;event handlers&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Now, imagine if we try to update the &lt;code&gt;counter&lt;/code&gt; state using &lt;code&gt;setCounter&lt;/code&gt; setter function two times sequentially. What would be the value of the &lt;code&gt;counter&lt;/code&gt; state after the second render?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// counter = 1
setCounter(counter +1)
setCounter(counter +1)
// counter = ?? 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Well, that&apos;s what we are going to discover in the next article, where we introduce &lt;code&gt;React State Batching&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Thank you for your attentive reading and happy coding 🧑‍💻.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-state-snapshots-explained.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-state-snapshots-explained.png" length="0" type="image/png"/></item><item><title>React&apos;s Three Phases: Complete Guide to Trigger, Render, and Commit</title><link>https://sidaliassoul.com/blog/react-three-phases-trigger-render-commit/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-three-phases-trigger-render-commit/</guid><description>Understand the React rendering process and how components are updated in the DOM, providing insights into optimizing performance.</description><pubDate>Wed, 02 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Did you know that a &lt;strong&gt;React&lt;/strong&gt; component can re-render while the corresponding displayed &lt;strong&gt;UI&lt;/strong&gt; segment has not been changed?&lt;/p&gt;
&lt;p&gt;I know &lt;strong&gt;when we say rendering, we instinctively think that something has to be printed on the screen&lt;/strong&gt;. But that&apos;s not necessarily the case for &lt;strong&gt;React&lt;/strong&gt; 🤯.&lt;/p&gt;
&lt;h2&gt;Why DOM Updates Are Expensive&lt;/h2&gt;
&lt;p&gt;Updating your application&apos;s &lt;strong&gt;UI&lt;/strong&gt;, which is displayed on your browser screen, involves &lt;strong&gt;performing a series of operations&lt;/strong&gt; on the &lt;strong&gt;DOM,&lt;/strong&gt; or the &lt;strong&gt;Document Object Model,&lt;/strong&gt; which is &lt;strong&gt;an object representation of the parsed HTML code that is required to display the UI&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If &lt;strong&gt;React&lt;/strong&gt; were updating the &lt;strong&gt;DOM&lt;/strong&gt; &lt;strong&gt;every time a component had re-rendered&lt;/strong&gt;, &lt;strong&gt;the number of DOM operations performed could become huge&lt;/strong&gt;. Therefore, your application&apos;s performance would be negatively affected.&lt;/p&gt;
&lt;p&gt;Moreover, we shall say that &lt;strong&gt;updating the DOM is considered a costly operation in general&lt;/strong&gt;. Especially &lt;strong&gt;if performed too often&lt;/strong&gt; because of the following reasons:&lt;/p&gt;
&lt;h3&gt;Browser Reflows&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;First, &lt;strong&gt;DOM&lt;/strong&gt; operations &lt;strong&gt;trigger browser reflows,&lt;/strong&gt; during which it &lt;strong&gt;has to recalculate the layout of the entire page, or a large part of it&lt;/strong&gt;. For example, when an element gets removed from the &lt;strong&gt;DOM&lt;/strong&gt;, &lt;strong&gt;the positions of the other elements need to be recalculated again&lt;/strong&gt;. The &lt;strong&gt;more elements on the page, the more expensive these re-calculations become&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Browser Repainting&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Secondly, after &lt;strong&gt;reflow&lt;/strong&gt;, the browser may need to &lt;strong&gt;repaint the affected parts&lt;/strong&gt; of the screen. &lt;strong&gt;Repainting&lt;/strong&gt; involves &lt;strong&gt;redrawing elements&lt;/strong&gt; (borders, shadows, colors, shapes, and so on). Despite being lighter than &lt;strong&gt;reflow,&lt;/strong&gt; it&apos;s &lt;strong&gt;still not counted as a trivial operation&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;DOM Updates are synchronous.&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Finally, in addition to &lt;strong&gt;reflow&lt;/strong&gt; and &lt;strong&gt;repaint&lt;/strong&gt;, &lt;strong&gt;DOM&lt;/strong&gt; updates are &lt;strong&gt;synchronous,&lt;/strong&gt; which means that they can &lt;strong&gt;block UI interactions&lt;/strong&gt; and ruin the entire user experience &lt;strong&gt;(UX).&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Well, fortunately &lt;strong&gt;React does not touch the DOM when a component renders&lt;/strong&gt;. &lt;strong&gt;Rendering&lt;/strong&gt; is nothing more than the process of &lt;strong&gt;calling your function component by React&lt;/strong&gt;, which is way faster than &lt;strong&gt;DOM&lt;/strong&gt; updates.&lt;/p&gt;
&lt;h2&gt;The Three Phases&lt;/h2&gt;
&lt;p&gt;Instead of updating the DOM on every render, &lt;strong&gt;React&lt;/strong&gt; is &lt;strong&gt;splitting the work into 3 phases&lt;/strong&gt;: &lt;strong&gt;trigger&lt;/strong&gt;, &lt;strong&gt;render,&lt;/strong&gt; and &lt;strong&gt;commit&lt;/strong&gt;. The &lt;strong&gt;DOM&lt;/strong&gt; updates are &lt;strong&gt;deferred&lt;/strong&gt; to the last phase (&lt;strong&gt;the commit phase&lt;/strong&gt;).&lt;/p&gt;
&lt;h3&gt;1. Trigger Phase&lt;/h3&gt;
&lt;p&gt;The trigger phase consists of asking React to render or re-render a specific component.&lt;/p&gt;
&lt;p&gt;A render can be triggered by &lt;strong&gt;two different reasons&lt;/strong&gt;:&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;Initial Render&lt;/strong&gt;:&lt;/h4&gt;
&lt;p&gt;Firstly, &lt;strong&gt;when the whole component tree gets initially rendered&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;As you may know, your app gets initially rendered via the &lt;strong&gt;React&lt;/strong&gt; root element, which is created by the &lt;strong&gt;createRoot&lt;/strong&gt; function that is imported from &quot;&lt;strong&gt;react-dom/client.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { StrictMode } from &apos;react&apos;
import { createRoot } from &apos;react-dom/client&apos;
import App from &apos;./App.tsx&apos;

const root = createRoot(document.getElementById(&apos;root&apos;)!);

root.render(
  &amp;lt;StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/StrictMode&amp;gt;,
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;strong&gt;createRoot&lt;/strong&gt; function receives the wrapper &lt;strong&gt;DOM&lt;/strong&gt; node, where the final rendered &lt;strong&gt;HTML&lt;/strong&gt; that corresponds to your component&apos;s tree needs to be injected (root &lt;strong&gt;div&lt;/strong&gt;). And then &lt;strong&gt;renders your component tree given the parent App component&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;So the first render happens when the &lt;strong&gt;React&lt;/strong&gt; root render method gets initially called.&lt;/p&gt;
&lt;h4&gt;&lt;strong&gt;State Updates&lt;/strong&gt;:&lt;/h4&gt;
&lt;p&gt;Secondly, once &lt;strong&gt;your component tree has been initially rendered, you can trigger further renders&lt;/strong&gt; by &lt;strong&gt;calling the setter function returned by the useState hook&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Whenever the setter function is called&lt;/strong&gt;, &lt;strong&gt;React&lt;/strong&gt; queues or schedules a future render. Even if you&apos;ve called the &lt;strong&gt;setter function&lt;/strong&gt; &lt;strong&gt;multiple times&lt;/strong&gt;, the &lt;strong&gt;new state&lt;/strong&gt; won&apos;t be reflected until the &lt;strong&gt;next render&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Put differently, using the &lt;strong&gt;setter function&lt;/strong&gt; means just asking &lt;strong&gt;React&lt;/strong&gt; for a future render while mentioning the state changes.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; will take that into consideration and schedule the next render with the &lt;strong&gt;new state value&lt;/strong&gt;. &lt;strong&gt;Consequently, it will update the parts of the JSX code that are derived from the new state&lt;/strong&gt; during the next render.&lt;/p&gt;
&lt;h3&gt;2. Render Phase&lt;/h3&gt;
&lt;p&gt;Now let&apos;s move into the second phase that comes after &lt;strong&gt;triggering a render&lt;/strong&gt;, which is obviously &lt;strong&gt;rendering&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;To put it in simple words, &lt;strong&gt;rendering is just when React decides to call your function component&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;As we saw earlier, a render can be triggered either on app start, during which the root object triggers the initial render of the whole component tree, or on demand when a state gets updated in a specific component.&lt;/p&gt;
&lt;p&gt;When a specific component&apos;s state changes, all of its direct or indirect children will re-render recursively. In other terms, if the grandpa re-renders, all of the descendant family will get re-rendered sequentially starting from the children to the grandchildren and so on.&lt;/p&gt;
&lt;p&gt;Each component in the tree will return the JSX code that corresponds to the UI segment that it is responsible for.&lt;/p&gt;
&lt;p&gt;As we saw in the JSX article, despite looking like &lt;strong&gt;HTML code,&lt;/strong&gt; it&apos;s just a &lt;strong&gt;JavaScript&lt;/strong&gt; language extension, meaning that it&apos;s getting converted into a bunch of objects representing the real &lt;strong&gt;HTML&lt;/strong&gt; DOM nodes.&lt;/p&gt;
&lt;p&gt;So during the initial render of the component&apos;s tree, React builds a &lt;strong&gt;virtual representation of the real DOM&lt;/strong&gt; as raw &lt;strong&gt;JavaScript&lt;/strong&gt; objects.&lt;/p&gt;
&lt;p&gt;When a given component re-renders because of a state update, the component and its descendants will re-render as we saw previously, so the &lt;strong&gt;JSX&lt;/strong&gt; returned by some components may differ compared with the initial re-render.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;React will keep track of all the changes that are caused by the re-renders&lt;/strong&gt; while &lt;strong&gt;calculating a minimal number of DOM operations that are needed to move from the previous state (before rendering) to the newest state (after rendering)&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;3. Commit Phase&lt;/h3&gt;
&lt;p&gt;After the process of re-rendering, during which &lt;strong&gt;React creates a bunch of objects representing the DOM elements&lt;/strong&gt; and &lt;strong&gt;calculates a lot of information regarding the minimal required DOM operations to get from the oldest state to the newest&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; will finally start modifying the &lt;strong&gt;DOM&lt;/strong&gt; during what is called the &lt;strong&gt;commit phase&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The commit phase happens in two cases:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Initial rendering:&lt;/strong&gt; Just after rendering or calling all the components in the tree, &lt;strong&gt;React&lt;/strong&gt; reads the collected information that consists of, remember, &lt;strong&gt;the constructed objects representing the DOM nodes&lt;/strong&gt;. And then uses the &lt;strong&gt;DOM&lt;/strong&gt; API to insert all the nodes inside the wrapping &lt;strong&gt;div&lt;/strong&gt; whose &lt;strong&gt;ID&lt;/strong&gt; is equal to &lt;strong&gt;root&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;When re-rendering:&lt;/strong&gt; &lt;strong&gt;React&lt;/strong&gt; will use the information collected during the &lt;strong&gt;rendering phase&lt;/strong&gt; and apply a minimal number of &lt;strong&gt;DOM&lt;/strong&gt; operations in order to make it match the latest rendering output.&lt;/p&gt;
&lt;p&gt;So React is smart enough to only change the &lt;strong&gt;DOM&lt;/strong&gt; nodes that have been modified during the previous phase.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;By &lt;strong&gt;delaying DOM operations to the commit phase&lt;/strong&gt; and &lt;strong&gt;calculating the optimal number of DOM operations after re-rendering&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; manages to achieve great performance while simplifying the process of &lt;strong&gt;UI&lt;/strong&gt; development by taking care of the &lt;strong&gt;complex stuff like DOM manipulation&lt;/strong&gt; and providing you, the user, with a &lt;strong&gt;simple and descriptive language&lt;/strong&gt; that allows you to model the &lt;strong&gt;UI&lt;/strong&gt; as a function of its state using &lt;strong&gt;React&lt;/strong&gt; components.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;UI = fn(State)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the next article, we will be diving more into the concept of &lt;strong&gt;state&lt;/strong&gt; in &lt;strong&gt;React&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Thank you for your attentive reading and happy coding.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-three-phases-trigger-render-commit.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>webdev</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-three-phases-trigger-render-commit.png" length="0" type="image/png"/></item><item><title>React useState Hook Tutorial: Complete Guide to Component State Management</title><link>https://sidaliassoul.com/blog/react-usestate-hook-state-management/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-usestate-hook-state-management/</guid><description>Learn how React components maintain and update their state, allowing you to create dynamic and interactive user interfaces.</description><pubDate>Wed, 26 Mar 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Modern web applications are &lt;strong&gt;highly interactive&lt;/strong&gt;; users can &lt;strong&gt;click on buttons, fill out forms, toggle navbars, play a video, and so on&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Interactivity&lt;/strong&gt; makes the &lt;strong&gt;UI&lt;/strong&gt;, therefore the &lt;strong&gt;React&lt;/strong&gt; components change as the time wheel rolls by.&lt;/p&gt;
&lt;p&gt;When you type on an &lt;strong&gt;input&lt;/strong&gt; field, the wrapper component should keep track of &lt;strong&gt;the last typed value&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If you &lt;strong&gt;toggle&lt;/strong&gt; a &lt;strong&gt;navbar&lt;/strong&gt;, it should &lt;strong&gt;always stay toggled&lt;/strong&gt; and never get reset back to its previous state as long as we&apos;ve never clicked on the toggle &lt;code&gt;button&lt;/code&gt; again.&lt;/p&gt;
&lt;p&gt;In other words, sometimes a &lt;strong&gt;React&lt;/strong&gt; component needs some kind of &lt;strong&gt;local and personal memory&lt;/strong&gt; to remember what&apos;s needed to &lt;strong&gt;accomplish its mission&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Understanding Component State&lt;/h2&gt;
&lt;p&gt;This specific type of memory is called a &lt;strong&gt;component&apos;s local state&lt;/strong&gt;, and it&apos;s today&apos;s article topic. So without any further ado, let&apos;s get started.&lt;/p&gt;
&lt;h2&gt;Building a Counter Component&lt;/h2&gt;
&lt;p&gt;Let&apos;s say that we want to create a basic &lt;strong&gt;Counter&lt;/strong&gt; component that supports &lt;strong&gt;incrementation, decrementation, and reset operations&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Or in other words, a &lt;strong&gt;React&lt;/strong&gt; component that &lt;strong&gt;renders a count variable&lt;/strong&gt; while &lt;strong&gt;providing buttons for incrementing, decrementing, and resetting that counter.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;count&lt;/strong&gt; variable is declared locally using the let keyword and then rendered in the JSX via the curly brackets syntax.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  let count;

  console.count(&quot;UI: Updated&quot;);

  return (
    &amp;lt;div&amp;gt;
    &amp;lt;div&amp;gt;Count is {count}&amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={(e)=&amp;gt;{
        count += 1;
        console.log(count)
      }}&amp;gt;Increment&amp;lt;/button&amp;gt;

      &amp;lt;button onClick={(e)=&amp;gt;{
        count -= 1;
        console.log(count)
      }}&amp;gt;Decrement&amp;lt;/button&amp;gt;

      &amp;lt;button onClick={(e)=&amp;gt;{
        count = 0;
        console.log(count)
      }}&amp;gt;Reset&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each &lt;strong&gt;button&lt;/strong&gt; is attached to an &lt;strong&gt;event handler&lt;/strong&gt; that changes the &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; variable depending on the operation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Adding one on incrementing,&lt;/strong&gt; &lt;strong&gt;subtracting one on the decrementation,&lt;/strong&gt; and &lt;strong&gt;resetting the variable to zero&lt;/strong&gt; when the reset button gets clicked.&lt;/p&gt;
&lt;p&gt;Now, let&apos;s &lt;strong&gt;try to increment&lt;/strong&gt; the &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; while checking the console logs in the inspect window in parallel.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/counter-example-no-use-state.png&quot; alt=&quot;Counter Example with a local variable&quot; /&gt;&lt;/p&gt;
&lt;p&gt;The &quot;&lt;strong&gt;count&quot;&lt;/strong&gt; variable is indeed getting incremented with every click, but the displayed &quot;count&quot; value in the UI is stuck at 0.&lt;/p&gt;
&lt;p&gt;In other words, &lt;strong&gt;the component is not re-rendering the JSX when we increment the variable&lt;/strong&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Notice also that the UI: Updated message got printed two times meaning that the component have only rendered one time. By default &lt;strong&gt;React&lt;/strong&gt; uses &lt;strong&gt;Strict mode&lt;/strong&gt; in development environment for debugging reasons, that&apos;s why the message got printed twice. In production environment, &lt;strong&gt;Strict mode&lt;/strong&gt; gets disabled, thus only 1 render will occur.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Come on, how is it even possible to call this framework &lt;strong&gt;React&lt;/strong&gt; if it&apos;s not reacting to the &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; variable changes by &lt;strong&gt;re-rendering the component and updating the UI&lt;/strong&gt;?&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/react-waiting-for-updates-local-variable.jpg&quot; alt=&quot;React waiting for a state update when you mutate a local variable&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Well, the reason behind that is that changes to the locally declared &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; &lt;strong&gt;variable&lt;/strong&gt; can&apos;t trigger a re-render. Or in other terms, &lt;strong&gt;no one is telling React that the &quot;count&quot; variable has changed&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Even if we suppose that changing the &quot;count&quot; variable directly will trigger a component&apos;s re-render&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; variable will be stuck at zero.&lt;/p&gt;
&lt;p&gt;The reason is when the component&apos;s code runs, the &quot;&lt;strong&gt;count&quot;&lt;/strong&gt; variable will be re-declared again and, therefore, re-initialized to zero.&lt;/p&gt;
&lt;p&gt;So to summarize all that has been said, we need two built-in mechanisms to make the counter-example work:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Something that tells &lt;strong&gt;React&lt;/strong&gt; that a given &lt;strong&gt;state variable&lt;/strong&gt; has changed, therefore triggering a component&apos;s re-render and then updating the &lt;strong&gt;UI&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;And a way to persist data or &lt;strong&gt;state&lt;/strong&gt; between the component&apos;s re-renders so that our &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; variable value will never get reset or lost between re-renders again.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Fortunately &lt;strong&gt;React&lt;/strong&gt; has to &lt;strong&gt;react&lt;/strong&gt; to this and provide a utility function named &lt;strong&gt;useState&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/react-provide-use-state.jpg&quot; alt=&quot;React Provides useState&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Using useState&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;import {useState} from &quot;react&quot;
function App(){
  const stateTuple = useState()
  const [state, setState] = stateTuple

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;useState&lt;/strong&gt; can be imported from &lt;strong&gt;&quot;react&quot;&lt;/strong&gt; and used inside any component to declare a &lt;strong&gt;local state&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;useState&lt;/strong&gt; returns what is known as a &lt;strong&gt;tuple,&lt;/strong&gt; or in other words, an &lt;strong&gt;array of two items&lt;/strong&gt;, the first being the &lt;strong&gt;state&lt;/strong&gt; variable that persists between re-renders, and the second one being a setter function, &quot;&lt;strong&gt;setState&lt;/strong&gt;,&quot; that updates the state while triggering a re-render.&lt;/p&gt;
&lt;p&gt;To make this more convenient, we usually use the array destructuring syntax to store the two returned array items in two different variables without a lot of boilerplate code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import {useState} from &quot;react&quot;
function App(){
  const [state, setState] = useState()
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The items are usually named &lt;strong&gt;variableName&lt;/strong&gt; followed by &lt;strong&gt;setVariableName,&lt;/strong&gt; but you&apos;re free to name them as you prefer.&lt;/p&gt;
&lt;p&gt;It&apos;s also worth mentioning that &lt;strong&gt;useState&lt;/strong&gt; accepts an argument that consists of the initial value of the state; for example, in our case, we want to declare a state variable named &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; and a corresponding setter function named &lt;strong&gt;&quot;setState&quot;&lt;/strong&gt; while ensuring that the &quot;&lt;strong&gt;count&quot;&lt;/strong&gt; variable defaults to zero.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const [count, setCount] = useState(0)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&apos;s refactor the event handlers to set the &lt;strong&gt;&quot;count&quot;&lt;/strong&gt; using the &quot;&lt;strong&gt;setCount&quot;&lt;/strong&gt; &lt;strong&gt;setter function&lt;/strong&gt; instead of &lt;strong&gt;mutating the variable directly&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  import {useState} from &apos;react&apos;;
  const [count, setCount] = useState(0)
  console.count(&quot;UI: Updated&quot;)

  return (
    &amp;lt;div&amp;gt;
    &amp;lt;div&amp;gt;Count is {count}&amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={()=&amp;gt;{
        setCount(count+1)
      }}&amp;gt;Increment&amp;lt;/button&amp;gt;

      &amp;lt;button onClick={()=&amp;gt;{
        setCount(count-1)
      }}&amp;gt;Decrement&amp;lt;/button&amp;gt;

      &amp;lt;button onClick={()=&amp;gt;{
        setCount(0)
      }}&amp;gt;Reset&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, let&apos;s try to increment, decrement, and reset the &quot;&lt;strong&gt;count.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/react-use-state-counter-example.png&quot; alt=&quot;useState counter example&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Unlike the previous example, now the &lt;strong&gt;UI&lt;/strong&gt; is &lt;strong&gt;reacting&lt;/strong&gt; to the &lt;strong&gt;count&lt;/strong&gt; variable &lt;strong&gt;updates&lt;/strong&gt; and &lt;strong&gt;changing whenever the count variable gets modified&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Or in other terms, &lt;strong&gt;the component re-renders when the &quot;count&quot; variable gets modified with the setter function&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Even though the code inside the component re-runs entirely when re-rendering, the state still gets persisted between all the re-renders.&lt;/p&gt;
&lt;h2&gt;Hooks Rules&lt;/h2&gt;
&lt;p&gt;In &lt;strong&gt;React&lt;/strong&gt;, any function starting with &lt;strong&gt;&quot;use&quot;&lt;/strong&gt; is called a &lt;strong&gt;hook&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Therefore, &lt;strong&gt;useState&lt;/strong&gt; is one of &lt;strong&gt;React&lt;/strong&gt;&apos;s built-in &lt;strong&gt;hooks&lt;/strong&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;In addition to the default &lt;strong&gt;hooks&lt;/strong&gt; that get shipped with react you&apos;re free to create your own but that&apos;s another topic for another article.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It&apos;s true that &lt;strong&gt;hooks&lt;/strong&gt; are ordinary &lt;strong&gt;JavaScript&lt;/strong&gt; functions, but you can&apos;t use them everywhere in your &lt;strong&gt;JavaScript&lt;/strong&gt; application.&lt;/p&gt;
&lt;p&gt;Any happy marriage implies adhering to a bunch of predefined constraints, and so too does your relationship with &lt;strong&gt;React&lt;/strong&gt; &lt;strong&gt;hooks&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The first rule is to always call your &lt;strong&gt;React&lt;/strong&gt; hooks at the top level of your component.&lt;/p&gt;
&lt;p&gt;In other words, just after the opening curly braces &quot;&lt;strong&gt;{}&quot;&lt;/strong&gt; of the component&apos;s function declaration.&lt;/p&gt;
&lt;h3&gt;First Rule&lt;/h3&gt;
&lt;p&gt;Don&apos;t even think about using hooks inside &lt;strong&gt;loops&lt;/strong&gt;, &lt;strong&gt;conditions&lt;/strong&gt;, &lt;strong&gt;nested functions&lt;/strong&gt;, &lt;strong&gt;try/catch/finally blocks&lt;/strong&gt;, or &lt;strong&gt;JSX markup.&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { useState } from &quot;react&quot;
function App(){
  // Loops ❌

  while(true){ // ❌
    const [counter,setCounter] = useState(0) 
  }

  for(let i=0;i&amp;lt;5;i++){  // ❌

    const [counter,setCounter] = useState(0)
  }
  do{ // ❌

    const [counter,setCounter] = useState(0)
  }while(true)
  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import { useState } from &quot;react&quot;

function App(){
  if(true){ // Conditions ❌
    const [counter,setCounter] = useState(0)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;import { useState } from &quot;react&quot;
function App(){
  // Try Catch blocks
  try{ // Try Catch, Finally blocks ❌
    const [counter,setCounter] = useState(0)   //  Try Catch blocks ❌
  }catch(error){

    const [counter,setCounter] = useState(0) // Try Catch blocks ❌
  }finally{

    const [counter,setCounter] = useState(0) // Try Catch, Finally blocks ❌
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead always use them at &lt;strong&gt;the top level&lt;/strong&gt; of your &lt;strong&gt;function component&lt;/strong&gt; &lt;strong&gt;before any early return statement&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import {useState} from &quot;react&quot;
function App(){
      const [counter,setCounter] = useState(0) // ✅

      if(true){ // Early return
        return null
      }

      const [counter,setCounter] = useState(0) // ❌
      
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Usually, &lt;strong&gt;React&lt;/strong&gt; will let you know when you&apos;ve broken one of these rules with a detailed error message.&lt;/p&gt;
&lt;h3&gt;Second Rule&lt;/h3&gt;
&lt;p&gt;The second rule is to never use &lt;strong&gt;hooks&lt;/strong&gt; in any other place other than a &lt;strong&gt;React&lt;/strong&gt; function component.&lt;/p&gt;
&lt;p&gt;Using them in an &lt;strong&gt;ordinary function&lt;/strong&gt;, &lt;strong&gt;class,&lt;/strong&gt; or &lt;strong&gt;object&lt;/strong&gt; will only &lt;strong&gt;cause you frustration and trouble&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import {useState} from &quot;react&quot;

function App(){
  const [counter,setCounter] = useState(0) // ✅
}

function add(a,b){

  const [counter,setCounter] = useState(0) // ❌
  return a + b;
}

class Counter{
  const [counter,setCounter] = useState(0) // ❌
}

const calculator = {
  add:(a,b)=&amp;gt;{
  const [counter,setCounter] = useState(0) // ❌
  }
  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;How State Updates Work&lt;/h3&gt;
&lt;p&gt;Now let&apos;s get back to our previous &lt;strong&gt;&quot;counter-example&quot;&lt;/strong&gt;, and break what&apos;s happening under the hood slowly.&lt;/p&gt;
&lt;p&gt;When we click on the increment &lt;strong&gt;button,&lt;/strong&gt; the &lt;strong&gt;click event&lt;/strong&gt; gets fired; therefore, &lt;strong&gt;the event handler will start running&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Inside the event handler&apos;s code, the &quot;&lt;strong&gt;setCount&quot;&lt;/strong&gt; function gets called with the current &lt;strong&gt;count&lt;/strong&gt; state value, which is equal to zero plus one, as an argument.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;setCount(count + 1) // count=0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Calling the latter triggers a second re-render or tells &lt;strong&gt;React,&lt;/strong&gt; &quot;Hey, some state got updated here; please re-render the component and then update the &lt;strong&gt;UI&lt;/strong&gt;.&quot;&lt;/p&gt;
&lt;p&gt;Even though the &quot;&lt;strong&gt;setCount&quot;&lt;/strong&gt; function executes on the current render, the &quot;&lt;strong&gt;count&quot;&lt;/strong&gt; state value will remain equal to 0 until the next render.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  // First Render

  //...code

  // count = 0

  return (
    &amp;lt;div&amp;gt;
    &amp;lt;div&amp;gt;Count is {count} {/* 0 */}&amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={()=&amp;gt;{
        setCount(count+1) // setCount(0+1)
        // count = 0 , It&apos;s scheduled to change on the Second render
      }}&amp;gt;Increment&amp;lt;/button&amp;gt;
      {/** ... code */}

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

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In other terms, React queues all the updates of the current render in memory until the next render happens, where the &lt;strong&gt;UI&lt;/strong&gt; will get constructed depending on the new state value.&lt;/p&gt;
&lt;p&gt;On the second render, the &quot;&lt;strong&gt;count&quot;&lt;/strong&gt; state will be incremented; therefore, it will be equal to 1, the component will execute from the top to the bottom, returning the &lt;strong&gt;JSX&lt;/strong&gt; with the updated &lt;strong&gt;count&lt;/strong&gt; state value, and finally &lt;strong&gt;React&lt;/strong&gt; will update the &lt;strong&gt;real&lt;/strong&gt; &lt;strong&gt;DOM&lt;/strong&gt; in the user&apos;s browser.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  // Second Render

  //...code

  // count = 1

  return (
    &amp;lt;div&amp;gt;
    &amp;lt;div&amp;gt;Count is {counter} {/* 1 */}&amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={()=&amp;gt;{
        setCount(count+1) // setCount(1+1)

        // count = 1 , It&apos;s scheduled to change on the Third render
      }}&amp;gt;Increment&amp;lt;/button&amp;gt;
      {/** ... code */}

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

}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Multiple Components and State&lt;/h3&gt;
&lt;p&gt;Let me ask you a question now. What would you expect if we had called the &lt;strong&gt;Counter&lt;/strong&gt; component two times in the &lt;strong&gt;App&lt;/strong&gt; component? What would happen if we incremented one of them?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Counter(){
  /*Previous counter code*/
}

function App(){
  return(
    &amp;lt;div&amp;gt;
      &amp;lt;Counter/&amp;gt;  {/* count = 1*/}
      &amp;lt;Counter/&amp;gt;  {/* count = 0 */}
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we have said, from the beginning the state is private and personal. So incrementing the first counter will only affect the first called component.&lt;/p&gt;
&lt;h3&gt;Multiple State Variables&lt;/h3&gt;
&lt;p&gt;Another question that may traverse your mind is, can we use more than one state in a &lt;strong&gt;React&lt;/strong&gt; component?&lt;/p&gt;
&lt;p&gt;The answer is absolutely yes, we can do that.&lt;/p&gt;
&lt;p&gt;Let&apos;s take this &quot;&lt;strong&gt;Greeting&quot;&lt;/strong&gt; component as an example.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function UserGreeting() {
  const [name, setName] = useState(&apos;Guest&apos;);
  const [showGreeting, setShowGreeting] = useState(true);
  
  return (
    &amp;lt;div&amp;gt;
      {showGreeting &amp;amp;&amp;amp; &amp;lt;p&amp;gt;Hello, {name}!&amp;lt;/p&amp;gt;}
      &amp;lt;button onClick={() =&amp;gt; setName(name === &apos;Guest&apos; ? &apos;User&apos; : &apos;Guest&apos;)}&amp;gt;
        Toggle Name
      &amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setShowGreeting(!showGreeting)}&amp;gt;
        {showGreeting ? &apos;Hide&apos; : &apos;Show&apos;} Greeting
      &amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here we are declaring two pieces of state: one holding the &lt;strong&gt;name,&lt;/strong&gt; which can be either &quot;&lt;strong&gt;Guest&quot;&lt;/strong&gt; or &quot;&lt;strong&gt;User,&quot;&lt;/strong&gt; and the other one is a &lt;strong&gt;boolean&lt;/strong&gt; named &lt;strong&gt;&quot;isGuest&quot;&lt;/strong&gt; controlling whether to show the greeting message or not.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  const [name, setName] = useState(&apos;Guest&apos;);
  const [showGreeting, setShowGreeting] = useState(true);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The component &lt;strong&gt;conditionally renders a greeting message&lt;/strong&gt; at the top along with &lt;strong&gt;two action buttons at the bottom&lt;/strong&gt;.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The greeting message is only shown when the &quot;&lt;strong&gt;showGreeting&quot;&lt;/strong&gt; state is set to &quot;&lt;strong&gt;true.&quot;&lt;/strong&gt; The message consists of a &quot;&lt;strong&gt;p&quot;&lt;/strong&gt; tag wrapping a &lt;strong&gt;&quot;Hello&quot;&lt;/strong&gt; string and the current &lt;strong&gt;name&lt;/strong&gt; state value.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;      {showGreeting &amp;amp;&amp;amp; &amp;lt;p&amp;gt;Hello, {name}!&amp;lt;/p&amp;gt;}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;The first action button is responsible for toggling the &lt;strong&gt;name&lt;/strong&gt; state between &quot;&lt;strong&gt;Guest&quot;&lt;/strong&gt; and &quot;&lt;strong&gt;User.&quot;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;      &amp;lt;button onClick={() =&amp;gt; setName(name === &apos;Guest&apos; ? &apos;User&apos; : &apos;Guest&apos;)}&amp;gt;
        Toggle Name
      &amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;The second one toggles the &quot;&lt;strong&gt;showGreeting&quot;&lt;/strong&gt; state between &lt;strong&gt;true&lt;/strong&gt; and &lt;strong&gt;false&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;      &amp;lt;button onClick={() =&amp;gt; setShowGreeting(!showGreeting)}&amp;gt;
        {showGreeting ? &apos;Hide&apos; : &apos;Show&apos;} Greeting
      &amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; is smart enough to determine which state variable corresponds to which &quot;&lt;strong&gt;useState&quot;&lt;/strong&gt; call as long as you follow the &lt;strong&gt;Law of Hooks.&lt;/strong&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; is internally relying on the order of &lt;strong&gt;useState&lt;/strong&gt; calls.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;With all that being said, we can conclude that using two &lt;strong&gt;states&lt;/strong&gt; or more is a completely viable and easily achievable option in &lt;strong&gt;React&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In the next article, we will be diving deeper into how &lt;strong&gt;React&lt;/strong&gt; goes from rendering to displaying the &lt;strong&gt;UI&lt;/strong&gt; on the user&apos;s browser screen.&lt;/p&gt;
&lt;p&gt;Thank you for your attentive reading and happy coding!&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-usestate-hook-state-management.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-usestate-hook-state-management.png" length="0" type="image/png"/></item><item><title>React Event Handlers Tutorial: Complete Guide to onClick and Event Handling</title><link>https://sidaliassoul.com/blog/react-event-handlers-onclick-tutorial/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-event-handlers-onclick-tutorial/</guid><description>Learn how to handle user interactions in React by implementing event handlers for clicks, form submissions, and more.</description><pubDate>Wed, 19 Mar 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;A &lt;strong&gt;button&lt;/strong&gt; is meant to be &lt;strong&gt;clicked&lt;/strong&gt;, and when it&apos;s clicked, we &lt;strong&gt;intrinsically&lt;/strong&gt; expect something to happen, right?&lt;/p&gt;
&lt;p&gt;Well, the thing that will happen is &lt;strong&gt;defined by you, the developer,&lt;/strong&gt; as a &lt;strong&gt;JavaScript&lt;/strong&gt; function doing something; let&apos;s say displaying an alert message as an example.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The function whose job is to respond to an event triggered by something like a user interaction such as clicking&lt;/strong&gt; is called an &lt;strong&gt;event handler&lt;/strong&gt;, and it&apos;s a normal &lt;strong&gt;JavaScript&lt;/strong&gt; function declared within the component. This special function can be attached to any &lt;strong&gt;JSX&lt;/strong&gt; element such as &lt;strong&gt;buttons&lt;/strong&gt;, &lt;strong&gt;divs&lt;/strong&gt;, &lt;strong&gt;inputs,&lt;/strong&gt; and so on.&lt;/p&gt;
&lt;p&gt;In this article, &lt;strong&gt;we will dive deeper into event handlers&lt;/strong&gt; while &lt;strong&gt;exploring important concepts&lt;/strong&gt; that every developer needs to master, such as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Passing event handlers between &lt;strong&gt;React&lt;/strong&gt; components.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Event propagation&lt;/strong&gt; and why understanding it is so important.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;And finally, how to stop event propagation and other browser default behaviors when needed.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So if that sounds interesting, let&apos;s dive in.&lt;/p&gt;
&lt;h2&gt;Event Handlers Basics&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; makes attaching an event handler to a &lt;strong&gt;JSX&lt;/strong&gt; element really straightforward.&lt;/p&gt;
&lt;p&gt;Let&apos;s say that we&apos;ve got a component rendering a &lt;strong&gt;button&lt;/strong&gt; named &lt;strong&gt;&quot;click me.&quot;&lt;/strong&gt; Let&apos;s define an &lt;strong&gt;event handler&lt;/strong&gt; named &lt;strong&gt;&quot;handleClick&quot;&lt;/strong&gt; as a locally declared function within the component as we&apos;ve discussed previously.&lt;/p&gt;
&lt;p&gt;Usually, the &lt;strong&gt;React&lt;/strong&gt; community follows the naming convention that cons&lt;strong&gt;i&lt;/strong&gt;sts of &lt;strong&gt;starting the event handler&apos;s name with &quot;handle&quot; followed by the event name&lt;/strong&gt;. Some examples of that include &lt;strong&gt;handleClick&lt;/strong&gt;, &lt;strong&gt;handleHover&lt;/strong&gt;, &lt;strong&gt;handleFocus,&lt;/strong&gt; and so on.&lt;/p&gt;
&lt;p&gt;Now, we just have to assign the event handler (aka our locally declared function) to a special type of &lt;strong&gt;prop&lt;/strong&gt; starting with &lt;strong&gt;&quot;on&quot;&lt;/strong&gt; and then followed by the name of the event, such as &lt;strong&gt;onClick&lt;/strong&gt;, &lt;strong&gt;onFocus&lt;/strong&gt;, &lt;strong&gt;onHover,&lt;/strong&gt; and so on. In our case let&apos;s pass it to onClick.&lt;/p&gt;
&lt;p&gt;A mistake that&apos;s often repeated by most beginners is calling the function instead of just assigning the function name.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Button(){

function handleClick(){
  alert(&quot;Stop Clicking&quot;)

}
return (
    &amp;lt;button onClick={handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt; {/* ✅ */}
    {/* &amp;lt;button onClick={handleClick()} /&amp;gt;Click me &amp;lt;/button&amp;gt; ❌ */ }
)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Doing so will just &lt;strong&gt;make the function run at every single render or component update,&lt;/strong&gt; which is obviously not our goal here.&lt;/p&gt;
&lt;p&gt;The function that is attached to the &lt;strong&gt;onClick&lt;/strong&gt; prop is going to get called. Consequently, the alert message will pop up only when the &lt;strong&gt;button&lt;/strong&gt; gets clicked by the user.&lt;/p&gt;
&lt;p&gt;What if our component receives a &lt;strong&gt;username&lt;/strong&gt; prop? Can we access it in the &lt;strong&gt;event handler&lt;/strong&gt;?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Button({username}){

function handleClick(){
  alert(&quot;Hi &quot;+ username)

}
return (
    &amp;lt;button onClick={handleClick}&amp;gt;Click me&amp;lt;/button&amp;gt; {/* ✅ */}
)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yes, actually that&apos;s one of the advantages of declaring an &lt;strong&gt;event handler&lt;/strong&gt; within the component. Doing so allows the &lt;strong&gt;event handler&lt;/strong&gt; to access its &lt;strong&gt;parent&apos;s outer scope variables or functions,&lt;/strong&gt; such as &lt;strong&gt;props&lt;/strong&gt; or any other stuff.&lt;/p&gt;
&lt;h3&gt;Passing Event Handlers as Props&lt;/h3&gt;
&lt;p&gt;Okay, now what if you wanted to use the &lt;strong&gt;Button&lt;/strong&gt; component in multiple places?&lt;/p&gt;
&lt;p&gt;Declaring &quot;&lt;strong&gt;handleClick&lt;/strong&gt;&quot; inside it makes it impossible to change the &lt;strong&gt;button&apos;s component&apos;s&lt;/strong&gt; primary behavior, which is reacting to different events differently depending on where it&apos;s used. Therefore, it becomes less reusable.&lt;/p&gt;
&lt;p&gt;So can we solve this with props? In addition to that, is it even possible to pass functions as props?&lt;/p&gt;
&lt;p&gt;Functions are first-class citizens in &lt;strong&gt;JavaScript&lt;/strong&gt;. Consequently, they can be passed to other functions, therefore, &lt;strong&gt;React&lt;/strong&gt; components. So it&apos;s obviously possible to do that.&lt;/p&gt;
&lt;p&gt;Now let&apos;s make our Button component accept a new prop called &lt;strong&gt;&quot;onClick,&quot;&lt;/strong&gt; assign it to the button&apos;s &quot;&lt;strong&gt;onClick&quot;&lt;/strong&gt; prop, and then declare a &lt;strong&gt;handleClick&lt;/strong&gt; event handler inside the parent component itself. And then pass it to the &lt;strong&gt;Button&lt;/strong&gt; child component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Button({username,onClick}){

return (
    &amp;lt;button onClick={onClick}&amp;gt;Click me&amp;lt;/button&amp;gt; 
)
}

function App(){

const username = &quot;Sid Ali&quot;

function handleClick(){
  alert(&quot;Hi &quot;+ username)

}

  return (
    &amp;lt;div&amp;gt;
    &amp;lt;Button onClick={handleClick} username={username} /&amp;gt;
    &amp;lt;/div&amp;gt;

  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;By convention &lt;strong&gt;event handler props&lt;/strong&gt; are named exactly as the &lt;strong&gt;JSX&lt;/strong&gt; elements &lt;strong&gt;built-in&lt;/strong&gt; &lt;strong&gt;events props&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;So they should start with &lt;strong&gt;on&lt;/strong&gt; followed by either the event name or the interaction that need to be performed such as &lt;strong&gt;onClick&lt;/strong&gt;, &lt;strong&gt;OnUploadFile&lt;/strong&gt;, &lt;strong&gt;onTryingToFindARandomName&lt;/strong&gt; and so on.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Event Propagation and Bubbling&lt;/h2&gt;
&lt;p&gt;Now that we&apos;ve tackled the basics of event handling, let&apos;s move on to a very important and interesting concept that is known as &lt;strong&gt;event bubbling or propagation&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;But before that, let me ask you a simple question.&lt;/p&gt;
&lt;p&gt;What will happen if you have clicked on the child component of two nested &lt;strong&gt;JSX&lt;/strong&gt; elements, both having an event attached to their &lt;strong&gt;onClick&lt;/strong&gt; prop? Which component will show its corresponding alert message?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Parent(){
  return (
    &amp;lt;div onClick={()=&amp;gt;alert(&quot;Hello From Parent&quot;)}&amp;gt;
      &amp;lt;Child1 /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

function Child(){
  return (
    &amp;lt;button onClick={()=&amp;gt;alert(&quot;Hello from Child&quot;)}&amp;gt;Click me&amp;lt;/button&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;-&amp;gt; (1) Hello from Child
-&amp;gt; (2) Hello from Parent 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The answer, as you may have guessed, is both but in a special order.&lt;/p&gt;
&lt;p&gt;The alert message corresponding to the &lt;strong&gt;child&lt;/strong&gt; component will get displayed first, and then the &lt;strong&gt;parent&lt;/strong&gt; will follow after that.&lt;/p&gt;
&lt;p&gt;We call what has just happened &lt;strong&gt;event propagation or bubbling&lt;/strong&gt;. We say that &lt;strong&gt;the click event has propagated from the child to the parent&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Stopping Event Propagation&lt;/h3&gt;
&lt;p&gt;If you happen to be bothered by such default behavior, you can stop the propagation by doing as follows:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Child(){
  return (
    &amp;lt;button onClick={(e)=&amp;gt;{
      e.stopPropagation()
      alert(&quot;Hello from Child&quot;)}
      }&amp;gt;Click me&amp;lt;/button&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Every &lt;strong&gt;event handler&lt;/strong&gt; has access to an optional &lt;strong&gt;e&lt;/strong&gt; argument which is a shorthand standing for &lt;strong&gt;event.&lt;/strong&gt; You can use this argument to either read information about the &lt;strong&gt;event&lt;/strong&gt; or perform actions on it.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Among those actions is being able to call the &lt;strong&gt;stopPropagation&lt;/strong&gt; method to prevent the event from &lt;strong&gt;bubbling up&lt;/strong&gt; to &lt;strong&gt;its parent&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Alternative to Propagation&lt;/h3&gt;
&lt;p&gt;To be in total control, you can stop the propagation and rely on passing props to decide whether you want to call the parent event handler or not.&lt;/p&gt;
&lt;p&gt;You can achieve that by &lt;strong&gt;passing the parent&apos;s event handler as a prop and then calling it after stopping the propagation and running some code&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Parent(){
  function handleClick(){
    alert(&quot;Hello From Parent&quot;)
  }
  return (
    &amp;lt;div onClick={handleClick}&amp;gt;
      &amp;lt;Child1  onClick={handleClick}/&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}

function Child({onClick}){
  return (
    &amp;lt;button onClick={(e)=&amp;gt;{
      e.stopPropagation();

      alert(&quot;Hello from Child&quot;);
      onClick()

    }}&amp;gt;Click me&amp;lt;/button&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;-&amp;gt; (1) Hello from Child
-&amp;gt; (2) Hello from Parent 
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Preventing Default Browser Behavior&lt;/h2&gt;
&lt;p&gt;In addition to propagation, there is another annoying event that you will definitely want to prevent.&lt;/p&gt;
&lt;p&gt;When you submit a form, by default the browser refreshes the page, therefore killing your entire &lt;strong&gt;React&lt;/strong&gt; application and probably causing some side effects, like smashing your keyboard from anger when that happens.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Form(){

  function handleSubmit(e){
    alert(&quot;Hello From Form&quot;)
  }

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/browser-refresh-meme.jpg&quot; alt=&quot;Browser Refresh Meme&quot; /&gt;&lt;/p&gt;
&lt;p&gt;So similarly to what we did to stop the propagation. All you need to do here is to go to the form&apos;s &lt;strong&gt;onSubmit&lt;/strong&gt;-attached event handler, make sure to define the &lt;strong&gt;event parameter e&lt;/strong&gt;, and then call the &lt;strong&gt;preventDefault&lt;/strong&gt; method on the &lt;strong&gt;e&lt;/strong&gt; object to &lt;strong&gt;prevent the default browser refresh behavior&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Form(){

  function handleSubmit(e){
    e.preventDefault(); // This line prevents the browser&apos;s default behavior ✅
    alert(&quot;Hello From Form&quot;)
  }

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;button&amp;gt;Submit&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Events are happening all the time in a &lt;strong&gt;highly interactive web application&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;But when an event fires, it&apos;s usually handled by modifying some components in the &lt;strong&gt;React&lt;/strong&gt; application tree. Think about it: a dropdown changes from toggled to none toggled depending on the number of times that it&apos;s clicked, which leads us to a fundamental concept that we haven&apos;t discussed yet until now&lt;/p&gt;
&lt;p&gt;In the next article of the series, we will finally explore how React &lt;strong&gt;reacts&lt;/strong&gt; and &lt;strong&gt;remembers&lt;/strong&gt; what has happened now and in the past after some series of interactions or events.&lt;/p&gt;
&lt;p&gt;Thank you for watching and happy coding!&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-event-handlers-onclick-tutorial.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-event-handlers-onclick-tutorial.png" length="0" type="image/png"/></item><item><title>React Rendering Lists Tutorial: Complete Guide to Map Method and Keys</title><link>https://sidaliassoul.com/blog/react-rendering-lists-map-keys-tutorial/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-rendering-lists-map-keys-tutorial/</guid><description>Learn how to efficiently render lists of data in React using array methods and keys for optimal performance.</description><pubDate>Wed, 12 Mar 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;In many situations you&apos;ll want to &lt;strong&gt;display multiple&lt;/strong&gt; items that &lt;strong&gt;share the same structure and styling&lt;/strong&gt; based on a collection of predefined data that might come from &lt;strong&gt;various sources,&lt;/strong&gt; including &lt;strong&gt;external APIs&lt;/strong&gt;, offline browser storages such as &lt;strong&gt;IndexedDB&lt;/strong&gt; or &lt;strong&gt;LocalStorage,&lt;/strong&gt; and so on.&lt;/p&gt;
&lt;p&gt;Even though the data might come from &lt;strong&gt;various sources,&lt;/strong&gt; it always ends up in a &lt;strong&gt;JavaScript array&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;So in this article we will learn &lt;strong&gt;how to render a list of components&lt;/strong&gt; or just raw &lt;strong&gt;JSX&lt;/strong&gt; codes given an &lt;strong&gt;array of data&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;And then we will understand how &lt;strong&gt;React&lt;/strong&gt; can track those &lt;strong&gt;rendered components&lt;/strong&gt; via something called &lt;strong&gt;keys&lt;/strong&gt;. So without any further ado, let&apos;s dive in.&lt;/p&gt;
&lt;p&gt;Take a look at this code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;ol&amp;gt;
  &amp;lt;li style={{...}} &amp;gt;Item 1&amp;lt;/li&amp;gt;
  &amp;lt;li style={{...}}&amp;gt;Item 2&amp;lt;/li&amp;gt;
  ...
  &amp;lt;li style={{...}} &amp;gt;Item N&amp;lt;/li&amp;gt;
&amp;lt;/ol&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Writing code like this is the fastest way to make your project unmaintainable.&lt;/p&gt;
&lt;p&gt;Let&apos;s say that you needed to &lt;strong&gt;render a list of items&lt;/strong&gt; that have the &lt;strong&gt;same styling and structure&lt;/strong&gt; but only &lt;strong&gt;differ in their content&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Solution: How to Map an Array of Item into JSX Code.&lt;/h2&gt;
&lt;p&gt;Instead of writing that whole code and repeating ourselves.&lt;/p&gt;
&lt;p&gt;We can just define an &lt;strong&gt;array&lt;/strong&gt; of strings that will host all of our data. And then use the &lt;code&gt;array&lt;/code&gt; built-in &lt;code&gt;map&lt;/code&gt; method to transform each element in the &lt;strong&gt;array&lt;/strong&gt; into a different shape.&lt;/p&gt;
&lt;p&gt;This is done by passing a &lt;strong&gt;callback function&lt;/strong&gt; that defines this transformation.&lt;/p&gt;
&lt;p&gt;The callback function will be written as follows: we take the function&apos;s argument, and then we return this &lt;code&gt;JSX&lt;/code&gt; code that represents the targeted markup of each array element.&lt;/p&gt;
&lt;p&gt;In our case we want to convert each item in the array from a string to JSX code, which consists of the &lt;code&gt;&amp;lt;li&amp;gt;&lt;/code&gt; tags wrapping the string.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  const  items = [&quot;item 1&quot;,&quot;item2&quot;,&quot;item 3&quot;]
  const JSXItems =  items.map(item=&amp;gt;(&amp;lt;li&amp;gt;{item}&amp;lt;/li&amp;gt;))
  // [&amp;lt;li&amp;gt;Item 1&amp;lt;/li&amp;gt;,&amp;lt;&amp;gt;Item 2&amp;lt;/li&amp;gt;,&amp;lt;&amp;gt;Item 3&amp;lt;/li&amp;gt;]

  return (
    /*...code*/
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;Keep in mind, that the map method keeps the original array intact, and returns a new array that we can store in a newly created variable.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;How to Render an Array of JSX Codes?&lt;/h2&gt;
&lt;p&gt;Okay, now what? We&apos;ve got an array of JSX elements. But how can we render that?&lt;/p&gt;
&lt;p&gt;&lt;code&gt;React&lt;/code&gt; can only render &lt;strong&gt;two things&lt;/strong&gt;: &lt;code&gt;JSX&lt;/code&gt; code or an &lt;code&gt;array&lt;/code&gt; of code. We can safely render the content of the new array directly in the JSX through the curly bracket syntax.&lt;/p&gt;
&lt;p&gt;The result will look like this.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  const  items = [&quot;item 1&quot;,&quot;item2&quot;,&quot;item 3&quot;]
  const JSXItems =  items.map(item=&amp;gt;(&amp;lt;li&amp;gt;{item}&amp;lt;/li&amp;gt;)) // array of JSX elements.
  // [&amp;lt;li&amp;gt;Item 1&amp;lt;/li&amp;gt;,&amp;lt;&amp;gt;Item 2&amp;lt;/li&amp;gt;,&amp;lt;&amp;gt;Item 3&amp;lt;/li&amp;gt;]

  return (
    &amp;lt;ol&amp;gt;
    {JSXItems}
    &amp;lt;/ol&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;A Richer Example: Rendering an Array of Todos!&lt;/h2&gt;
&lt;p&gt;Now that we&apos;ve got the basics, let&apos;s deepen our understanding by walking through a more involved example.&lt;/p&gt;
&lt;p&gt;Picture this: we have an array of todo objects, each one possessing the following attributes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;An &lt;strong&gt;ID&lt;/strong&gt; that uniquely identifies each object.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A &lt;code&gt;todo name&lt;/code&gt;, &lt;code&gt;description&lt;/code&gt; and a &lt;code&gt;boolean&lt;/code&gt; variable representing whether a given todo is completed or not.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;const todos = [
  {
    id: 1,
    name: &quot;todo 1&quot;,
    description: &quot;todo 1 description&quot;,
    completed: false,
  },
  {
    id: 2,
    name: &quot;todo 2&quot;,
    description: &quot;todo 2 description&quot;,
    completed: true,
  },
  {
    id: 3,
    name: &quot;todo 3&quot;,
    description: &quot;todo 3 description&quot;,
    completed: false,
  },
];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Similar to our previous example, we can use the &lt;code&gt;map()&lt;/code&gt; array method to transform this array of objects into an array of JSX elements. In this snippet, each element represents the JSX structure for an individual todo item.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const todosJSX =  todos.map(item=&amp;gt;(
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;{item.name}&amp;lt;/h2&amp;gt;
        &amp;lt;p&amp;gt;{item.description}&amp;lt;/p&amp;gt;
        &amp;lt;p&amp;gt;{item.completed ? &quot;✅&quot;  : &quot;❌&quot;}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now let&apos;s just render the array in the &lt;strong&gt;App&lt;/strong&gt; component&apos;s &lt;strong&gt;JSX&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  // ...code for todos
const todosJSX =  todos.map(item=&amp;gt;(
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;{item.name}&amp;lt;/h2&amp;gt;
        &amp;lt;p&amp;gt;{item.description}&amp;lt;/p&amp;gt;
        &amp;lt;p&amp;gt;{item.completed ? &quot;✅&quot;  : &quot;❌&quot;}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;))
  return (
    &amp;lt;div&amp;gt;
      {todosJSX}
    &amp;lt;/div&amp;gt;

  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That&apos;s how easy it is to render an array of objects. It&apos;s that simple; just map it to &lt;strong&gt;JSX&lt;/strong&gt; elements, and you&apos;re good to go 😄.&lt;/p&gt;
&lt;p&gt;Now as the JSX returned by the &lt;strong&gt;map&apos;s callback function&lt;/strong&gt; is getting quite long and messy, let&apos;s substitute it or move it into its own react component&lt;/p&gt;
&lt;p&gt;First, create a &lt;strong&gt;&quot;TodoItem&quot;&lt;/strong&gt; component, receiving the necessary props and returning the previous JSX code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function TodoItem({name,description,completed}){

  return (
      &amp;lt;div&amp;gt;
        &amp;lt;h2&amp;gt;{name}&amp;lt;/h2&amp;gt;
        &amp;lt;p&amp;gt;{description}&amp;lt;/p&amp;gt;
        &amp;lt;p&amp;gt;{completed ? &quot;✅&quot;  : &quot;❌&quot;}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then let&apos;s call it in the map&apos;s &lt;strong&gt;callback function&lt;/strong&gt; and pass the props by spreading the todo object instead of passing each attribute separately.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  // ...code for todos
const todosJSX =  todos.map(todo=&amp;gt;(&amp;lt;TodoItem {...todo}/&amp;gt;))
  return (
    &amp;lt;div&amp;gt;
      {todosJSX}
    &amp;lt;/div&amp;gt;

  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;As you can see below spreading the todo object makes the component more readable and maintainable.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;pre&gt;&lt;code&gt;const todosJSX =  todos.map(todo=&amp;gt;(&amp;lt;TodoItem title={todo.title} description={todo.description} completed={todo.completed} /&amp;gt;)) 

// VS
const todosJSX =  todos.map(todo=&amp;gt;(&amp;lt;TodoItem {...todo}/&amp;gt;)) // ✅ Better and more concise
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now our code is much cleaner and easier to read.&lt;/p&gt;
&lt;h1&gt;How can React track many rendered components?&lt;/h1&gt;
&lt;p&gt;So what are keys? Why are they so important to React?&lt;/p&gt;
&lt;p&gt;When calling the same component twice or rendering an array of components, it&apos;s important to pass a unique key to each component.&lt;/p&gt;
&lt;p&gt;In fact, if you try to render a list of items without passing the &lt;strong&gt;key&lt;/strong&gt; prop into each one. The following warning gets displayed in your browser console.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;⚠️ &lt;strong&gt;React Warning:&lt;/strong&gt; Each child in a list should have a unique &quot;key&quot; prop.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;When using the &lt;code&gt;map&lt;/code&gt; method to render an &lt;code&gt;array&lt;/code&gt; of items, we should always pass a &lt;code&gt;string&lt;/code&gt; or a &lt;code&gt;number&lt;/code&gt; &lt;code&gt;key&lt;/code&gt; prop that &lt;strong&gt;uniquely identifies each item among other items in the array&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;keys&lt;/strong&gt; help &lt;strong&gt;React&lt;/strong&gt; to understand which array item each component corresponds to. Or you can think of it as a way to link your array data to the rendered components or &lt;strong&gt;JSX&lt;/strong&gt; items.&lt;/p&gt;
&lt;p&gt;That may seem not important when the &lt;strong&gt;array&lt;/strong&gt; is not changing. But if it &lt;strong&gt;gets mutated or changed&lt;/strong&gt; by either &lt;strong&gt;sorting it, deleting or inserting an item, and so on&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;React&lt;/strong&gt; can have a hard time tracking items because, &lt;strong&gt;by default, it&apos;s using the item&apos;s array index&lt;/strong&gt; as a &lt;strong&gt;key,&lt;/strong&gt; which is obviously not stable when deleting or inserting items or sorting the array.&lt;/p&gt;
&lt;p&gt;The &lt;strong&gt;keys should also be stable&lt;/strong&gt;, or in other terms, &lt;strong&gt;they should not change every time the component gets rendered&lt;/strong&gt; in order to optimize updating the DOM tree, and therefore your application&apos;s performance when displayed on the user browser.&lt;/p&gt;
&lt;p&gt;The easiest way to make sure that the &lt;strong&gt;ID&lt;/strong&gt; is stable is to &lt;strong&gt;include it in the data itself, as we did previously when defining the todo list item object&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Right inside the &lt;strong&gt;&quot;map&apos;s&quot;&lt;/strong&gt; callback function, let&apos;s assign the &lt;code&gt;todo.id&lt;/code&gt; attribute to the component&apos;s key prop.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const todosJSX =  todos.map(todo=&amp;gt;(&amp;lt;TodoItem key={todo.id} {...todo}/&amp;gt;)) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The same thing applies if &lt;strong&gt;JSX&lt;/strong&gt; code was returned; just pass the &lt;code&gt;key&lt;/code&gt; prop to the upper wrapping element as shown below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const todosJSX =  todos.map(item=&amp;gt;(
      &amp;lt;div key={todo.id}&amp;gt;
        &amp;lt;h2&amp;gt;{item.name}&amp;lt;/h2&amp;gt;
        &amp;lt;p&amp;gt;{item.description}&amp;lt;/p&amp;gt;
        &amp;lt;p&amp;gt;{item.completed ? ✅  : ❌}&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;An interesting case that we should absolutely highlight here is when returning multiple &lt;strong&gt;JSX&lt;/strong&gt; items, we&apos;re required to use the fragment syntax because JSX does not allow returning multiple children, as you might know if you&apos;ve read the previous &lt;a href=&quot;./jsx-tutorial-react-javascript-guide.md&quot;&gt;JSX&lt;/a&gt; article.&lt;/p&gt;
&lt;p&gt;If you have tried to set the prop &lt;strong&gt;key&lt;/strong&gt; to the shorthand version of the &lt;strong&gt;React&lt;/strong&gt; fragment syntax, your editor will highlight it as a syntax error. Because that&apos;s not allowed.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Test({id}){

  return (
    &amp;lt;key = {id}&amp;gt; {/* Not allowed ❌*/}
    &amp;lt;h1&amp;gt;Title&amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;Random description text&amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Instead, you&apos;re required to use the longer version, which consists of wrapping your returned children with the &lt;strong&gt;&quot;React.Fragment&quot;&lt;/strong&gt; tag.&lt;/p&gt;
&lt;p&gt;Then you can pass the key prop as you usually do with any JSX tag or component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React from &quot;react&quot;
function Test({id}){

  return (
    &amp;lt;React.Fragment key = {id}&amp;gt; {/*  allowed ✅*/}
    &amp;lt;h1&amp;gt;Title&amp;lt;/h1&amp;gt;
    &amp;lt;div&amp;gt;Random description text&amp;lt;/div&amp;gt;
    &amp;lt;/React.Fragment&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h1&gt;Conclusion&lt;/h1&gt;
&lt;p&gt;So that&apos;s how you simply render lists in &lt;strong&gt;React&lt;/strong&gt;: just map your array to JSX code, create new subcomponents as needed, and most importantly, &lt;strong&gt;never forget your keys&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;We’ve got our keys and our components, and our list is rendering perfectly. &lt;strong&gt;But there is one critical detail we’ve skipped.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The user can now see its todos, but what if he wanted to complete a todo? He needs to click on a &quot;complete todo&quot; button, right? Doing so will fire what&apos;s known as a browser event.&lt;/p&gt;
&lt;p&gt;In the next article we&apos;re going to &lt;strong&gt;unveil how we can seamlessly respond to those events&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Thank you for your attentive reading, and happy coding 🧑‍💻.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-rendering-lists-map-keys-tutorial.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-rendering-lists-map-keys-tutorial.png" length="0" type="image/png"/></item><item><title>React Conditional Rendering: Complete Guide with If Statements and JSX</title><link>https://sidaliassoul.com/blog/react-conditional-rendering-guide/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-conditional-rendering-guide/</guid><description>Learn how to render different UI elements based on conditions, a key technique for creating dynamic React applications.</description><pubDate>Wed, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;A &lt;strong&gt;React&lt;/strong&gt; component is a &lt;strong&gt;building block&lt;/strong&gt; that runs &lt;strong&gt;JavaScript logic&lt;/strong&gt; and then returns the UI code in a special &lt;strong&gt;HTML-like&lt;/strong&gt; syntax known as &lt;strong&gt;JSX&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Some &lt;strong&gt;UI&lt;/strong&gt; elements like &lt;strong&gt;dropdowns&lt;/strong&gt;, &lt;strong&gt;navbars,&lt;/strong&gt; and so on need to &lt;strong&gt;display different things&lt;/strong&gt; depending on &lt;strong&gt;different conditions&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;In a &lt;strong&gt;React&lt;/strong&gt; component there are two different ways to conditionally render the &lt;strong&gt;UI:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;The first one is using &lt;strong&gt;if&lt;/strong&gt; statements directly in the function&apos;s body and returning different &lt;strong&gt;JSX&lt;/strong&gt; codes depending on the &lt;strong&gt;conditions&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The second approach consists of directly &lt;strong&gt;embedding the conditions in the&lt;/strong&gt; &lt;code&gt;JSX&lt;/code&gt; code within &lt;strong&gt;curly braces&lt;/strong&gt; &lt;code&gt;{}&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this article, we&apos;re going to explore both cases and master &lt;strong&gt;JSX&lt;/strong&gt; conditional rendering.&lt;/p&gt;
&lt;h2&gt;Conditional Rendering with If Statements&lt;/h2&gt;
&lt;p&gt;With these core concepts in mind, let&apos;s look at a practical example where an &lt;strong&gt;emoji component&lt;/strong&gt; receives a &lt;strong&gt;&quot;type&quot;&lt;/strong&gt; input prop that can be either &lt;strong&gt;&quot;angry&quot;&lt;/strong&gt; or &lt;strong&gt;&quot;smile&lt;/strong&gt;.&quot;&lt;/p&gt;
&lt;p&gt;The corresponding &lt;strong&gt;emoji&lt;/strong&gt; gets rendered depending on the value of &lt;strong&gt;&quot;type.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We have &lt;strong&gt;two ways&lt;/strong&gt; to achieve this in &lt;strong&gt;React&lt;/strong&gt;:&lt;/p&gt;
&lt;p&gt;Right in the emoji component&apos;s body, we can use a &lt;strong&gt;branching control flow statement&lt;/strong&gt; such as an &lt;strong&gt;&quot;if&quot;&lt;/strong&gt; or &quot;&lt;strong&gt;switch case&quot;&lt;/strong&gt; to return the right &lt;strong&gt;emoji&apos;s&lt;/strong&gt; &lt;strong&gt;JSX&lt;/strong&gt; code depending on the value of &lt;strong&gt;&quot;type.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Emoji({type}: {type: &apos;angry&apos; | &apos;smile&apos;}) {
  if(type === &apos;angry&apos;) {  
    return (
      &amp;lt;div&amp;gt;....&amp;lt;/div&amp;gt;
    );
  } else if (type === &apos;sad&apos;) {
    return &amp;lt;div&amp;gt;,....&amp;lt;/div&amp;gt;;
  } else {
    console.warn(&quot;An invalid type prop was passed to Emoji component&quot;);
    return null;
  }
}

function App() {
  return (
    &amp;lt;div style={{display: &apos;flex&apos;, gap: &apos;20px&apos;}}&amp;gt;
      &amp;lt;Emoji type=&quot;angry&quot; /&amp;gt;
      &amp;lt;Emoji type=&quot;sad&quot; /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then inside the &lt;strong&gt;app&lt;/strong&gt; component, we can &lt;strong&gt;call the component multiple times&lt;/strong&gt; while passing &lt;strong&gt;different values&lt;/strong&gt; to the &lt;strong&gt;&quot;type&quot;&lt;/strong&gt; prop.&lt;/p&gt;
&lt;p&gt;That&apos;s nice and all, but imagine if we needed to update the style of one &lt;strong&gt;&quot;div.&quot;&lt;/strong&gt; With the current setup, we will have to add the styles to every if statement branch, which is &lt;strong&gt;repetitive&lt;/strong&gt; and &lt;strong&gt;inconvenient&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;One solution for that is to store the emoji in a &lt;strong&gt;shared local variable,&lt;/strong&gt; and then depending on the &lt;strong&gt;type&lt;/strong&gt; prop value, we assign the corresponding emoji.&lt;/p&gt;
&lt;p&gt;After that we can wrap the value stored in the variable in a &lt;strong&gt;common shared &quot;div.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Emoji({type}: {type: &apos;angry&apos; | &apos;smile&apos;}) {
  let emoji;
  if(type === &apos;angry&apos;) {
    emoji = &quot;...&quot;;
  } else if (type === &apos;sad&apos;) {
    emoji = &quot;...&quot;;
  } else {
    console.warn(&quot;An invalid type prop was passed to Emoji component&quot;);
    return &amp;lt;&amp;gt;Wrong emoji type&amp;lt;/&amp;gt;;
  }
  return &amp;lt;div style=&quot;&quot;&amp;gt;{emoji}&amp;lt;/div&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That was conditional rendering in the &lt;strong&gt;JavaScript&lt;/strong&gt; &lt;strong&gt;land&lt;/strong&gt;, let&apos;s now explore conditionally displaying elements &lt;strong&gt;directly inside&lt;/strong&gt; the &lt;code&gt;JSX&lt;/code&gt; code.&lt;/p&gt;
&lt;h2&gt;Conditional Rendering in JSX&lt;/h2&gt;
&lt;p&gt;If anything that you put inside the JSX curly braces syntax should always return an expression, is it possible to embed a condition directly within it?&lt;/p&gt;
&lt;p&gt;Well, if you&apos;re thinking about an &lt;strong&gt;if statement, then&lt;/strong&gt; the answer is no, because as the name implies, it&apos;s a statement. In other words, it does not return anything.&lt;/p&gt;
&lt;p&gt;Hopefully, JavaScript has our backs covered with what&apos;s known as a ternary operator, which is a short way of representing an if statement that always returns something; it&apos;s an expression!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;condition ? exprIfTrue : exprIfFalse;
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;You can read it as: &lt;code&gt;if&lt;/code&gt; some condition is &lt;code&gt;true&lt;/code&gt; (&lt;strong&gt;question mark&lt;/strong&gt;) &lt;code&gt;return&lt;/code&gt; this expression &lt;code&gt;else&lt;/code&gt; (&lt;strong&gt;colon&lt;/strong&gt;) return this alternative expression.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;For example, let&apos;s say that we want to know the user&apos;s &lt;strong&gt;age category&lt;/strong&gt; and then store it in a variable; we can use a &lt;strong&gt;ternary operator,&lt;/strong&gt; which reads as follows: &lt;strong&gt;If age is greater than or equal to 18, return &quot;adult&quot;; else, return &quot;minor.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const userAgeCategory = age &amp;gt;= 18 ? &quot;adult&quot; : &quot;minor&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using the ternary operator inside &lt;strong&gt;JSX&lt;/strong&gt; will save us from the burden of creating a &lt;strong&gt;shared local variable&lt;/strong&gt; as we did previously or duplicating the styles everywhere. Therefore, making the component more maintainable.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Emoji({type}: {type: &apos;angry&apos; | &apos;smile&apos;}) {
  return &amp;lt;div style=&quot;&quot;&amp;gt;{type === &apos;angry&apos; ? &quot;...&quot; : &quot;...&quot;}&amp;lt;/div&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Using the Logical AND Operator&lt;/h2&gt;
&lt;p&gt;While the ternary operator is great for conditions that switch between returning two values. It can be verbose for hide/display-like conditions. Let me explain.&lt;/p&gt;
&lt;p&gt;Let&apos;s say that we&apos;ve got an &lt;strong&gt;isUserLoggedIn&lt;/strong&gt; &lt;strong&gt;boolean&lt;/strong&gt; variable, and we want to display the &lt;strong&gt;emojis&lt;/strong&gt; list only &lt;strong&gt;when the user is logged in&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;We can easily do that with the &lt;strong&gt;ternary operator by&lt;/strong&gt; displaying the emoji list when the &lt;code&gt;isLoggedIn&lt;/code&gt; variable is set to it &lt;code&gt;true&lt;/code&gt; and returning &lt;code&gt;null&lt;/code&gt; when it&apos;s not.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;isLoggedIn ? () : null
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Setting &lt;strong&gt;&quot;null&quot;&lt;/strong&gt; like that sounds verbose, right? Let&apos;s make it more concise by using the &lt;strong&gt;&quot;&amp;amp;&amp;amp;&quot;&lt;/strong&gt; operator to only render the list when the &lt;code&gt;isLoggedIn&lt;/code&gt; variable gets evaluated to &lt;strong&gt;&quot;true.&quot;&lt;/strong&gt; By default &lt;strong&gt;JavaScript&lt;/strong&gt; ignores the second side of an &lt;code&gt;and&lt;/code&gt; operator if the first side is set to &lt;strong&gt;&quot;false.&quot;&lt;/strong&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Note that we should only use the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator when we&apos;re absolutely sure that the left hand side of the expression is not a number.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;A common mistake is to use a &lt;code&gt;number&lt;/code&gt; as the condition, that works for most of the cases because &lt;code&gt;Javascript&lt;/code&gt; will automatically convert any type used there into a &lt;code&gt;boolean&lt;/code&gt; but if it&apos;s of a number type and its value is equal to &lt;code&gt;0&lt;/code&gt;. JavaScript will treat it a &lt;strong&gt;&quot;0&quot;&lt;/strong&gt; string.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/zero-hi-javascript-meme.jpg&quot; alt=&quot;Zero Hi Javascript Meme&quot; /&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;To fix that we can either add the negation operator &lt;code&gt;!&lt;/code&gt; two times just before the &lt;code&gt;number&lt;/code&gt; or convert the number into a condition by &lt;strong&gt;comparing it with another&lt;/strong&gt; &lt;strong&gt;&quot;Number&quot;&lt;/strong&gt;. For example, we can compare the age variable with 18: &lt;strong&gt;&quot;age &amp;gt;= 18&quot;&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;So with conditional rendering, we can make a &lt;code&gt;React&lt;/code&gt; component display different things depending on a bunch of conditions. Those conditions are either defined on the &lt;strong&gt;&quot;JavaScript Logic&quot;&lt;/strong&gt; side just before rendering the &lt;strong&gt;JSX&lt;/strong&gt; or are directly embedded &lt;strong&gt;in the JSX markup&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;While conditional rendering allows us to make decisions about what component should be rendered, they are not sufficient alone to deal with real-world data.&lt;/p&gt;
&lt;p&gt;Real-world data often comes in collections of items such as an array of products, customers, and so on. So are the missing constructs that we need to master to avoid repeating ourselves when deleting such cases?&lt;/p&gt;
&lt;p&gt;Yes, you guessed it right. In the next article, we&apos;re going to learn about another type of control flow statement. The kind that are not meant for making decisions but for not repeating ourselves. Yes, we are talking about loops in React.&lt;/p&gt;
&lt;p&gt;Until then, happy coding.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-conditional-rendering-guide.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-conditional-rendering-guide.png" length="0" type="image/png"/></item><item><title>PROPS in React explained.</title><link>https://sidaliassoul.com/blog/react-props-tutorial-passing-data/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-props-tutorial-passing-data/</guid><description>Learn how to pass data between React components using props, a fundamental concept for building dynamic and reusable components.</description><pubDate>Wed, 26 Feb 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;If you want to pass information from a parent component to a child component in React, props are exactly what you&apos;re looking for.&lt;/p&gt;
&lt;p&gt;As you may know, in &lt;code&gt;React&lt;/code&gt; we represent the user interface as components that are nested within each other, forming a &lt;code&gt;tree&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Each &lt;strong&gt;component&lt;/strong&gt; is responsible for its own &lt;code&gt;Markup&lt;/code&gt; and logic.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;React&lt;/code&gt; follows a &lt;code&gt;unidirectional data flow model&lt;/code&gt;, meaning that information can only be passed from &lt;strong&gt;parent components&lt;/strong&gt; to &lt;strong&gt;child components&lt;/strong&gt;. In other words, the data only flows in one direction, starting from the top of the tree to the bottom.&lt;/p&gt;
&lt;h2&gt;Passing Props Between Components&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;function ChildComponent() {
  return &amp;lt;h1&amp;gt;&amp;lt;/h1&amp;gt;;
}

function ParentComponent() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Props are the medium that allow us to send data from a parent component to a child component. So how can we possibly do that in code?&lt;/p&gt;
&lt;p&gt;Passing props from one component to another is straightforward. And here&apos;s how it&apos;s done:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Pass the data as attributes, similar to how you would pass &lt;code&gt;normal attributes&lt;/code&gt; to an &lt;code&gt;HTML&lt;/code&gt; tag element. Here we are passing a &lt;code&gt;content&lt;/code&gt; attribute with a value of &lt;code&gt;test.&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Now, let&apos;s add a &lt;code&gt;props&lt;/code&gt; parameter to the child component so that it can access the &lt;code&gt;content&lt;/code&gt; attribute that we&apos;ve passed before.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Finally, make the &lt;code&gt;ChildComponent&lt;/code&gt; render the &lt;code&gt;content&lt;/code&gt; value within an h1 tag.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;function ChildComponent(props) {
  return &amp;lt;h1&amp;gt;{props.content}&amp;lt;/h1&amp;gt;;
}

function ParentComponent() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent content=&quot;test&quot;/&amp;gt;
    &amp;lt;/div&amp;gt;
  );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It&apos;s also possible to access the &lt;code&gt;content&lt;/code&gt; attribute more conveniently using the destructuring syntax.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function ChildComponent({content}) {
  return &amp;lt;h1&amp;gt;{content}&amp;lt;/h1&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unlike normal &lt;code&gt;HTML&lt;/code&gt; attributes, &lt;code&gt;props&lt;/code&gt; can include any &lt;code&gt;JavaScript&lt;/code&gt; value such as: &lt;code&gt;arrays&lt;/code&gt;, &lt;code&gt;functions&lt;/code&gt;, or even &lt;code&gt;JSX&lt;/code&gt; code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function handleClick(){
console.log(&quot;Clicked!&quot;)
}
return(

&amp;lt;ChildComponent content=&quot;test&quot; arr={[1,2,3]} onClick={handleClick}/&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Prop Forwarding and Spread Operator&lt;/h2&gt;
&lt;p&gt;Okay, now let&apos;s say that we have 3 levels of nesting:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;A parent component &lt;code&gt;App&lt;/code&gt; that renders a component named &lt;code&gt;ChildComponent1&lt;/code&gt; while passing 3 props to it: a title, a description and an image.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;On the other hand, The &lt;code&gt;ChildComponent1&lt;/code&gt; renders the content of the &lt;code&gt;title&lt;/code&gt; inside an &lt;code&gt;h1&lt;/code&gt; tag and then forwards the &lt;code&gt;description&lt;/code&gt; and the &lt;code&gt;image&lt;/code&gt; props to a third component named &lt;code&gt;ChildComponent2&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;App -{title,img,description}--&amp;gt; ChildComponent1 --{description,image}-&amp;gt; ChildComponent2 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This can quickly get cumbersome as the number of forwarded &lt;code&gt;props&lt;/code&gt; increases. Moreover, the components become less resistant to changes when we want to forward more props.&lt;/p&gt;
&lt;p&gt;So instead of forwarding the &lt;code&gt;props&lt;/code&gt; manually like that&lt;/p&gt;
&lt;p&gt;We can only &lt;strong&gt;destructure&lt;/strong&gt; the &lt;code&gt;title&lt;/code&gt;, and use the spread operator syntax to store the remaining &lt;code&gt;props&lt;/code&gt; in an object called &lt;code&gt;restProps&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;After that we can pass the rest props to the &lt;code&gt;ChildComponent2&lt;/code&gt; using this syntax &lt;code&gt;&amp;lt;ChildComponent2 {...restProps}/&amp;gt;.&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function ParentComponent() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;ChildComponent1
        title={&quot;This is a message from component 1&quot;}
        description={&quot;description&quot;}
        image={&amp;lt;img src=&quot;...lorem picsum&quot; alt=&quot;image alt&quot; /&amp;gt;}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

function ChildComponent1({ title, ...restProps }) {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{title}&amp;lt;/h1&amp;gt;
      &amp;lt;ChildComponent2 {...restProps} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

function ChildComponent2({ description, image }) {
  return (
    &amp;lt;div&amp;gt;
      {description}
      {image}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Children Props and Layout Components&lt;/h2&gt;
&lt;p&gt;Some &lt;code&gt;HTML&lt;/code&gt; tags can wrap other elements within them. Can we achieve that with components? Or in other words, is it possible for a parent component to act as the layout that wraps a child component?&lt;/p&gt;
&lt;p&gt;To make a component &lt;strong&gt;wrap other components&lt;/strong&gt; or any &lt;code&gt;JSX&lt;/code&gt; code, we need to use a special &lt;code&gt;prop&lt;/code&gt; called &lt;code&gt;children.&lt;/code&gt; And as the name implies, it stores all the &lt;code&gt;JSX&lt;/code&gt; code that is wrapped by the component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function ChildComponent(){
  return (
  &amp;lt;div&amp;gt;I&apos;m a just a child&amp;lt;/div&amp;gt;
  )

}
function WrapperComponent({ children }) { // 
---
----- Higher order component
  return (
  &amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;I&apos;m the one who wraps...&amp;lt;/h1&amp;gt;
    {children}
    &amp;lt;h1&amp;gt;I&apos;m the one who knocks...&amp;lt;/h1&amp;gt;
  &amp;lt;div/&amp;gt;
  );
}

function App(){

return (
  &amp;lt;HigherOrderComponent&amp;gt;
    &amp;lt;&amp;gt;
    &amp;lt;ChildComponent/&amp;gt;
    &amp;lt;button&amp;gt;click me&amp;lt;/button&amp;gt;
    &amp;lt;/&amp;gt;

  &amp;lt;/HigherOrderComponent&amp;gt;

)

}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Your &lt;code&gt;React&lt;/code&gt; component would be nothing more than a static snippet if it weren&apos;t for &lt;code&gt;React&lt;/code&gt; props, which make it possible to reuse components in different scenarios.&lt;/p&gt;
&lt;p&gt;But what if a component receives an&lt;code&gt;isLoggedIn&lt;/code&gt; boolean value prop and needs to show either a &lt;code&gt;Login&lt;/code&gt; button or a &lt;code&gt;Logout&lt;/code&gt; button depending on that value?&lt;/p&gt;
&lt;p&gt;That&apos;s where conditional rendering comes in!&lt;/p&gt;
&lt;p&gt;In the next article, we will learn how to &lt;strong&gt;display different elements&lt;/strong&gt; depending on specific &lt;strong&gt;conditions&lt;/strong&gt;, using either &lt;code&gt;if&lt;/code&gt; statements within the &lt;code&gt;JavaScript logic&lt;/code&gt; of the component or a &lt;code&gt;ternary operator&lt;/code&gt; inside the &lt;code&gt;Markup&lt;/code&gt; itself.&lt;/p&gt;
&lt;p&gt;Until then, happy coding 🧑‍💻.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-props-tutorial-passing-data.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-props-tutorial-passing-data.png" length="0" type="image/png"/></item><item><title>Master JSX in 8 Minutes (Before You Write Your Next React Component) - React Tutorial</title><link>https://sidaliassoul.com/blog/jsx-tutorial-react-javascript-guide/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/jsx-tutorial-react-javascript-guide/</guid><description>Master JSX, the syntax extension for JavaScript that makes writing React components more intuitive and efficient.</description><pubDate>Wed, 19 Feb 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;So what the heck is JSX? And what does it have to do with HTML?&lt;/p&gt;
&lt;p&gt;&lt;code&gt;JSX&lt;/code&gt; is a syntax extension for &lt;code&gt;JavaScript&lt;/code&gt;. Yes, you heard it right: it&apos;s an extension of &lt;code&gt;JavaScript&lt;/code&gt; not &lt;code&gt;HTML&lt;/code&gt;, despite what many people think. This means that &lt;code&gt;JSX&lt;/code&gt; is eventually converted into valid &lt;code&gt;JavaScript&lt;/code&gt; code 😮.&lt;/p&gt;
&lt;p&gt;Under the hood, the conversion is handled by compilers like &lt;code&gt;Babel&lt;/code&gt; or &lt;code&gt;SWC&lt;/code&gt;. Consequently, the entire component tree representing our &lt;code&gt;App&lt;/code&gt; is transformed into &lt;code&gt;JavaScript&lt;/code&gt;. These objects are understood by the browser and used by the &lt;code&gt;React&lt;/code&gt; runtime to render the final &lt;code&gt;HTML&lt;/code&gt; code.&lt;/p&gt;
&lt;p&gt;For example, the code below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Image() {
  return &amp;lt;img alt=&quot;Blog post image&quot; src=&quot;https://picsum.photos/500/400&quot; /&amp;gt;;
}

function App(){
    return (
        &amp;lt;Image/&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;...will be converted by &lt;code&gt;Babel&lt;/code&gt; or &lt;code&gt;SWC&lt;/code&gt; into this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { jsx as _jsx } from &quot;react/jsx-runtime&quot;;

function Image() {
  return /*#__PURE__*/ _jsx(&quot;img&quot;, {
    alt: &quot;Blog post image&quot;,
    src: &quot;https://picsum.photos/500/400&quot;,
  });
}
function App() {
  return /*#__PURE__*/ _jsx(Image, {});
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;__jsx&lt;/code&gt; is imported from the &lt;code&gt;react/jsx-runtime&lt;/code&gt;;it&apos;s used to build and return the object representing the &lt;code&gt;JSX&lt;/code&gt; node.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We use &lt;code&gt;JSX&lt;/code&gt; for its conciseness. It&apos;s easier to read and write because it closely resembles the final &lt;code&gt;HTML&lt;/code&gt; that will be shipped to the user&apos;s browser.&lt;/p&gt;
&lt;p&gt;In this article, we will walk through everything you need to know about &lt;code&gt;JSX&lt;/code&gt; including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;The specific syntax rules that distinguish it from &lt;code&gt;HTML&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;How to embed &lt;code&gt;JavaScript&lt;/code&gt; using the curly brace syntax.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;JSX vs HTML: Key Differences&lt;/h2&gt;
&lt;p&gt;At first glance, &lt;code&gt;JSX&lt;/code&gt; looks like &lt;code&gt;HTML&lt;/code&gt;. In reality, its strictness may easily break your code if you&apos;re not careful.&lt;/p&gt;
&lt;p&gt;So the first rule is simple: just be strict with your tags and you&apos;ll be fine&lt;/p&gt;
&lt;p&gt;The rule consists of always closing tags, including self-closing ones like &lt;code&gt;&amp;lt;img/&amp;gt;&lt;/code&gt; or wrapping tags like &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;s.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
 return (
   &amp;lt;div&amp;gt; // ✅

   &amp;lt;img&amp;gt; // ❌
   &amp;lt;img/&amp;gt; // ✅

   &amp;lt;/div&amp;gt; // ✅
 )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In addition to being strict with the tags themselves, &lt;code&gt;JSX&lt;/code&gt; also has some special rules regarding their attributes. Instead of kabab-case in &lt;code&gt;HTML&lt;/code&gt;, you must use camel case when defining attributes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;button tab-index={0}&amp;gt; &amp;lt;/button&amp;gt;  // Kabab case ❌
&amp;lt;button tabIndex={0}&amp;gt; &amp;lt;/button&amp;gt;  // Camel case ✅
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that &lt;code&gt;JavaScript&lt;/code&gt;&apos;s reserved keywords are not allowed as attribute names. As an example of that, the &lt;code&gt;class&lt;/code&gt; keyword that is used to define classes is not allowed. That&apos;s why you need to use &lt;code&gt;className&lt;/code&gt; instead.&lt;/p&gt;
&lt;p&gt;As bonus information, there is one exception to the above rule, which is attributes that start with either &lt;code&gt;data-*&lt;/code&gt; or &lt;code&gt;aria-*&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;div class=&quot;...&quot;&amp;gt; &amp;lt;/div&amp;gt;  // ❌
&amp;lt;div className=&quot;...&quot;&amp;gt; &amp;lt;/div&amp;gt; // ✅
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Moreover, when declaring a component we also do it in camel case, while making sure that the first character is in uppercase. Bonus: That&apos;s actually called Pascal case!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function my_component() {
  /*...*/
} // Snake case ❌
function MyComponent() {
  /*...*/
} // Camel case ✅
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, let me ask you a question, can a &lt;code&gt;JavaScript&lt;/code&gt; function return multiple objects without wrapping them in an array or a parent object?-- No that&apos;s a syntax error right?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function invalidFunction() {
  return { key: &quot;sidali&quot; }, { key: &quot;I don&apos;t know&quot; }; // ❌
}

function validFunction() {
  return [{ key: &quot;Neovim&quot; }, { key: &quot;Btw&quot; }]; // ✅
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using a &lt;code&gt;div&lt;/code&gt; as a wrapper can be annoying sometimes, especially when styling elements. Instead, there is a built-in &lt;code&gt;React&lt;/code&gt; component that literally does nothing but virtually wrapping its children without even showing in the browser &lt;code&gt;DOM&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;You can use it this way. Or more concisely using empty tags &lt;code&gt;&amp;lt;&amp;gt;&amp;lt;/&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React from &apos;react&apos;
function CorrectComponent1(){ // ✅
  return (
    &amp;lt;React.Fragment&amp;gt;
      &amp;lt;h1&amp;gt;Title&amp;lt;/h1&amp;gt;
      &amp;lt;div&amp;gt;Description &amp;lt;/div&amp;gt;
    &amp;lt;/React.Fragment&amp;gt;
  )

// Or more concisely

function CorrectComponent2(){ // ✅
  return (
    &amp;lt;&amp;gt;
      &amp;lt;h1&amp;gt;Title&amp;lt;/h1&amp;gt;
      &amp;lt;div&amp;gt;Description &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  )
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Using JavaScript in JSX&lt;/h2&gt;
&lt;p&gt;Sure we can perform any kind of &lt;code&gt;JavaScript&lt;/code&gt; logic in the function&apos;s body before returning the &lt;code&gt;JSX&lt;/code&gt; including if statements, for loops and so on.&lt;/p&gt;
&lt;p&gt;But is there a built-in way to use &lt;code&gt;JavaScript&lt;/code&gt; or reference a &lt;code&gt;JavaScript&lt;/code&gt; value or object from within the &lt;code&gt;JSX&lt;/code&gt; code itself?&lt;/p&gt;
&lt;p&gt;Yes, and it&apos;s pretty simple; just use the curly bracket syntax &lt;code&gt;{}&lt;/code&gt; and then reference any variable, value, function call, or any expression from the &lt;code&gt;JavaScript world 🌎&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Rather than hardcoding the title value in the &lt;code&gt;Markup&lt;/code&gt; here, we can store the &lt;code&gt;h1&lt;/code&gt; tag&apos;s inner content in a &lt;code&gt;JavaScript&lt;/code&gt; variable as a string.&lt;/p&gt;
&lt;p&gt;And then reference it in the &lt;code&gt;Markup&lt;/code&gt;, using the curly bracket syntax like this.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  const title = &quot;This is my first react component&quot;;

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{title}&amp;lt;/h1&amp;gt;
      &amp;lt;ol&amp;gt;
        &amp;lt;li&amp;gt;Wake up&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Code&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Eat&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Sleep&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Repeat&amp;lt;/li&amp;gt;
      &amp;lt;/ol&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Think of the curly braces as a return statement. Anything that returns a string or &lt;code&gt;JSX&lt;/code&gt; code can be used inside them.&lt;/p&gt;
&lt;p&gt;Including functions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  const title = &quot;This is my first react component&quot;;
  const createTitle = (title) =&amp;gt; &amp;lt;h1&amp;gt;{title}&amp;lt;/h1&amp;gt;;

  return (
    &amp;lt;div&amp;gt;
      {createTitle(title)}
      &amp;lt;ol&amp;gt;
        &amp;lt;li&amp;gt;Wake up&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Code&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Eat&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Sleep&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Repeat&amp;lt;/li&amp;gt;
      &amp;lt;/ol&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And variables.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const var1 = &amp;lt;h1&amp;gt;This is my first react component&amp;lt;/h1&amp;gt;;
const var2 = (
  &amp;lt;div&amp;gt;
    {var1}
    &amp;lt;ol&amp;gt;
      &amp;lt;li&amp;gt;Wake up&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Code&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Eat&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Sleep&amp;lt;/li&amp;gt;
      &amp;lt;li&amp;gt;Repeat&amp;lt;/li&amp;gt;
    &amp;lt;/ol&amp;gt;
  &amp;lt;/div&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Beware of using if statements or loops inside the &lt;code&gt;JSX&lt;/code&gt;. Only values, variables and expressions are allowed!&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;return (
if(true){   ❌



}else{

}

for (){}  ❌

while(){} ❌


)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Is it possible to reference attributes and styles?&lt;/p&gt;
&lt;p&gt;All attributes except &lt;code&gt;style&lt;/code&gt; can be set to strings, using the curly braces syntax.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){

      const className = &quot;cool-div&quot;

    return(
    &amp;lt;&amp;gt;
      &amp;lt;div className={className}&amp;gt;&amp;lt;/div&amp;gt;
      &amp;lt;/&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In standard &lt;code&gt;HTML&lt;/code&gt; we set the &lt;code&gt;style&lt;/code&gt; attribute as a string that looks like this;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;div style=&quot;background-color:black; color:pink&quot;/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But things are a bit different, in the &lt;code&gt;JSX&lt;/code&gt; realm.&lt;/p&gt;
&lt;p&gt;We need to pass an object, that includes your &lt;code&gt;CSS&lt;/code&gt; properties and values as key-value pairs. Such as the keys are written in camel case instead of kabab-case.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/* CSS kebab-case */
background-color: black;
color: pink;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;function App(){

    const style = {
      backgroundColor: &apos;black&apos;,
      color: &quot;pink&quot;
    };

    return(
      &amp;lt;div style={style}/&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Often people get tripped up by these double curly braces &lt;code&gt;{{}}&lt;/code&gt;. They think that it&apos;s a special &lt;code&gt;JSX&lt;/code&gt; syntax. But it&apos;s actually just a regular JavaScript object being passed inside the curly brackets.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;img style={{ backgroundColor: &quot;red&quot; }} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;function App() {
  const styleObj = { backgroundColor: &quot;red&quot; };

  return (
    &amp;lt;img style={styleObj} /&amp;gt; // Instead of style={{backgroundColor:&apos;red&apos;}}
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Congratulations! You&apos;ve just earned a new badge: JSX Syntax Wizard! Now that you learned how the &lt;code&gt;JSX&lt;/code&gt; magic works under the hood and gone through its spell book. You&apos;re officially ready to write clean, error-free React components.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;But here&apos;s the catch: a Button component is practically useless if you can&apos;t reuse it with different titles, Right?&lt;/p&gt;
&lt;p&gt;We need some sort of mechanism that allows us to pass data to a React component in order to make it &lt;code&gt;generic&lt;/code&gt; and &lt;code&gt;reusable&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;In other words, we need to be able to pass a &lt;code&gt;title&lt;/code&gt; argument to the Button component!&lt;/p&gt;
&lt;p&gt;That&apos;s exactly what we are going to explore in the next article: we will learn about component arguments, also known as Props.&lt;/p&gt;
&lt;p&gt;Until then... happy coding.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/jsx-tutorial-react-javascript-guide.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/jsx-tutorial-react-javascript-guide.png" length="0" type="image/png"/></item><item><title>Creating Your First React Component is EASY</title><link>https://sidaliassoul.com/blog/first-react-component-tutorial/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/first-react-component-tutorial/</guid><description>Learn how to create and use React components, the building blocks of any React application.</description><pubDate>Wed, 12 Feb 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Before creating your first component, you need a project, right? And honestly, what&apos;s better than a single command to do so, thanks to Vite CLI?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm create vite@latest
# Or
npm create vite@latest
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Going through the installation wizard steps should be straightforward, but if this is your first time exploring the React or the Node.js world, I highly advise you to check out the previous article in the series.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello-world/
├── public/
│   └── vite.svg
├── src/
│   ├── App.css
│   ├── App.tsx
│   ├── index.css
│   ├── main.tsx
│   └── assets/
│       └── react.svg
├── node_modules/
│   └── ...
├── .gitignore
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this article, you&apos;ll learn all you need to know about creating React components.&lt;/p&gt;
&lt;p&gt;Without any further ado let&apos;s dive in.&lt;/p&gt;
&lt;h2&gt;Creating Your First React Component&lt;/h2&gt;
&lt;p&gt;Now that we&apos;ve initialized our &lt;strong&gt;Vite&lt;/strong&gt; project, let&apos;s jump over to the &lt;strong&gt;App.tsx&lt;/strong&gt; file, located within the &lt;strong&gt;src&lt;/strong&gt; directory.&lt;/p&gt;
&lt;p&gt;Once you&apos;ve done so, you&apos;ll notice that &lt;strong&gt;Vite&lt;/strong&gt; comes with a predefined counter-example.&lt;/p&gt;
&lt;p&gt;As you can see, a React component is just a simple JavaScript function that starts with a capital letter and returns a code that looks just like HTML.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App() {
  const [count, setCount] = useState(0);
  return (
    &amp;lt;&amp;gt;
      {/** more code here ... */}
      &amp;lt;div className=&quot;card&quot;&amp;gt;
        &amp;lt;button onClick={() =&amp;gt; setCount((count) =&amp;gt; count + 1)}&amp;gt;
          count is {count}
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      {/** more code here ... */}
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Simplifying the App Component&lt;/h2&gt;
&lt;p&gt;Let&apos;s simplify this code by deleting everything inside the &lt;strong&gt;App&lt;/strong&gt; function and making it return a simple container &lt;strong&gt;div&lt;/strong&gt; that wraps an &lt;strong&gt;h1&lt;/strong&gt; header and an unordered list &lt;strong&gt;ol&lt;/strong&gt; with a few random list elements &lt;code&gt;li&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function App(){
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;This is my first react component&amp;lt;/h1&amp;gt;
      &amp;lt;ol&amp;gt;
        &amp;lt;li&amp;gt;Wake up&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Code&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Eat&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Sleep&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Repeat&amp;lt;/li&amp;gt;
      &amp;lt;/ol&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Creating a New Image Component&lt;/h2&gt;
&lt;p&gt;When implementing UI interfaces in React code, we tend to mentally break it into many components. So how can we create another component that renders a random image and then reuse it inside the App component?&lt;/p&gt;
&lt;p&gt;As we said before, it&apos;s a matter of wrapping your HTML in a function.&lt;/p&gt;
&lt;p&gt;Let&apos;s place it just above the App component. The component returns an img HTML tag with the following attributes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;An alt attribute to support screen readers.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;And an src attribute that we will set equal to a URL generated by Lorem Picsum. -- It&apos;s a website where you can get a URL that loads a random image every time the page gets refreshed.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;function Image(){
  return &amp;lt;img alt=&quot;Blog post image&quot; src=&quot;https://picsum.photos/500/400&quot; /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;We didn&apos;t have to use the parentheses in the &lt;code&gt;Image&lt;/code&gt; component because the returned code is only written in a single line, in contrast with the &lt;code&gt;App&lt;/code&gt; component where we had to use parentheses because the code spanned &lt;strong&gt;more than one line&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Using the Image Component in App&lt;/h2&gt;
&lt;p&gt;Next, let&apos;s use it in &lt;code&gt;App&lt;/code&gt;. We can call it as we call a normal function inside of the returned HTML, but there is a more optimized way to do it, which is using this tag syntax &lt;code&gt;&amp;lt;Image/&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Image() {
  return &amp;lt;img alt=&quot;Blog post image&quot; src=&quot;https://picsum.photos/500/400&quot; /&amp;gt;;
}
function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;This is my first react component&amp;lt;/h1&amp;gt;
      &amp;lt;Image /&amp;gt;
      &amp;lt;ol&amp;gt;
        &amp;lt;li&amp;gt;Wake up&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Code&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Eat&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Sleep&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Repeat&amp;lt;/li&amp;gt;
      &amp;lt;/ol&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Running the Development Server&lt;/h2&gt;
&lt;p&gt;The code is ready; all that remains is to start the development server by running the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm run dev
# or
npm run dev
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Subsequently, we need to head into &lt;code&gt;http://localhost:5173&lt;/code&gt; and inspect the page.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/inspect-content-vite-first-component.png&quot; alt=&quot;First component preview&quot; /&gt;&lt;/p&gt;
&lt;p&gt;React injects the final HTML into a div known as the root div.&lt;/p&gt;
&lt;p&gt;As you can see, the HTML that is returned by the &lt;strong&gt;App&lt;/strong&gt; component and its child &lt;code&gt;Image&lt;/code&gt; component got merged together and then injected inside the &lt;code&gt;root&lt;/code&gt; &lt;code&gt;div&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/first-component-root-div-content.png&quot; alt=&quot;First component root div preview&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Organizing Components into Separate Files&lt;/h2&gt;
&lt;p&gt;While this works for a small demo, in a real web application, defining all the components in a single app is neither practical nor scalable.&lt;/p&gt;
&lt;p&gt;So let&apos;s create a &lt;code&gt;image.tsx&lt;/code&gt; file at the same directory level as &lt;strong&gt;app.tsx&lt;/strong&gt;, then just copy the &lt;strong&gt;Image function&lt;/strong&gt; declaration into its own dedicated file.&lt;/p&gt;
&lt;p&gt;Every file in &lt;code&gt;Javascript&lt;/code&gt; is considered its own closed module. So anything that is declared there is not accessible unless we explicitly export it.&lt;/p&gt;
&lt;h2&gt;Exporting Components&lt;/h2&gt;
&lt;p&gt;There are two ways to export our component:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We can add the export keyword next to it, and then import it in &lt;code&gt;app.tsx&lt;/code&gt; like this:&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;code&gt;image.tsx&lt;/code&gt; file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export Image;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;app.tsx&lt;/code&gt; file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { Image } from &quot;./image.tsx&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This approach is called normal exporting; a file can have many normal exports.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import {C1, C2 , C3} from &quot;file.tsx&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;We can also add the default keyword before the function name when exporting it to indicate that this component is a default export for the image.tsx file.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;code&gt;image.tsx&lt;/code&gt; file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export default Image;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;app.tsx&lt;/code&gt; file:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import Image from &quot;./image.tsx&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As the name implies, a file can only have a single default export.&lt;/p&gt;
&lt;h2&gt;Bonus Performance Information&lt;/h2&gt;
&lt;p&gt;Before moving on, there is one common mistake that can silently kill your app&apos;s performance: &lt;strong&gt;never declare a component inside another component.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Doing this forces &lt;strong&gt;React&lt;/strong&gt; to treat the inner component as &quot;brand new&quot; on every single update. This destroys any chance of caching or optimization, leading to potential performance issues.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;export function App(){
  // ❌
  function SubComponent(){
    return (
      &amp;lt;div&amp;gt;{/* code... */}&amp;lt;/div&amp;gt;
    )
  }
  return ( /*code...*/);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;HTML&lt;/code&gt; Files can get really big, and just making sure that tags are closing properly is honestly a big drag.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;React&lt;/code&gt; takes a modular approach by dividing the problem of building complex &lt;strong&gt;interactive web pages&lt;/strong&gt; into smaller &lt;strong&gt;sub-problems&lt;/strong&gt; or &lt;strong&gt;building blocks&lt;/strong&gt; known as &lt;code&gt;components&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;But there&apos;s an important point that we avoided talking about during this article.&lt;/p&gt;
&lt;p&gt;Can you guess? -- Yes, that&apos;s right; we kept saying &quot;HTML-like code.&quot; But we never explained why.&lt;/p&gt;
&lt;p&gt;Well, because that&apos;s not HTML code; it&apos;s actually a syntax extension of JavaScript, and it&apos;s called JSX!&lt;/p&gt;
&lt;p&gt;In the next article of the series, we will reveal &lt;strong&gt;more secrets&lt;/strong&gt; 🤫 about this mystery. Until then, happy coding.&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/first-react-component-tutorial.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>tutorial</category><enclosure url="https://sidaliassoul.com/open-graph/blog/first-react-component-tutorial.png" length="0" type="image/png"/></item><item><title>Just Created Your React Project? Don&apos;t PANIC, here&apos;s every file explained</title><link>https://sidaliassoul.com/blog/react-project-structure-explained/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/react-project-structure-explained/</guid><description>Understand the structure of a React project, how components interact, and the flow of data through a React application.</description><pubDate>Wed, 29 Jan 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;You just created your first React project. Hopefully using &lt;code&gt;Vite&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm create vite@latest
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But you stumbled upon a bunch of weird files and folders.&lt;/p&gt;
&lt;p&gt;So you started clicking around, trying to connect the dots, but the more files you opened, the more lost you felt.&lt;/p&gt;
&lt;p&gt;We&apos;re going to break down every single file, one by one, while building a mental map of how they connect.&lt;/p&gt;
&lt;h2&gt;Project Structure Overview&lt;/h2&gt;
&lt;p&gt;At first glance we can see:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Three main folders &lt;code&gt;src&lt;/code&gt;, &lt;code&gt;public&lt;/code&gt; and &lt;code&gt;node_modules&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Various config files that we can edit to customize our project.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;hello-world/
├── public/
│   └── vite.svg
├── src/
│   ├── App.css
│   ├── App.tsx
│   ├── index.css
│   ├── main.tsx
│   └── assets/
│       └── react.svg
├── node_modules/
│   └── ...
├── .gitignore
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Configuration Files&lt;/h2&gt;
&lt;h3&gt;.gitignore&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;.gitignore&lt;/code&gt; configuration file is used to tell Git which files and directories should be ignored when staging or committing your changes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# All the directories or files listed below will be ignored by git
node_modules
dist
dist-ssr
*.local
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;package.json&lt;/h3&gt;
&lt;p&gt;So what about the &lt;code&gt;package.json&lt;/code&gt; file?&lt;/p&gt;
&lt;p&gt;Picture it this way: it&apos;s like a library&apos;s index: it lists all the top-level dependencies of the project.&lt;/p&gt;
&lt;p&gt;As any package that you install may also have its own dependencies, which are known as &lt;code&gt;peer&lt;/code&gt; or &lt;code&gt;transitive&lt;/code&gt; dependencies&lt;/p&gt;
&lt;p&gt;A &lt;code&gt;.lock&lt;/code&gt; file is constantly managed and updated by your chosen package manager.&lt;/p&gt;
&lt;p&gt;In fact, it&apos;s automatically updated every time you install dependencies by running either&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install &amp;lt;package-name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;name&quot;: &quot;hello-world&quot;,
  &quot;private&quot;: true,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;type&quot;: &quot;module&quot;,
  &quot;scripts&quot;: {
    &quot;dev&quot;: &quot;vite&quot;,
    &quot;build&quot;: &quot;tsc &amp;amp;&amp;amp; vite build&quot;,
    &quot;preview&quot;: &quot;vite preview&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;typescript&quot;: &quot;~5.8.3&quot;,
    &quot;vite&quot;: &quot;^6.3.5&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In addition to listing top-level dependencies, the &lt;code&gt;package.json&lt;/code&gt; file also exposes scripts, which are commands that you can run on the terminal, such as:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;npm run dev&lt;/code&gt; which starts the development server&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;npm run build&lt;/code&gt; which generates the production-ready bundle.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;node_modules&lt;/h3&gt;
&lt;p&gt;So if the &lt;code&gt;package.json&lt;/code&gt; file only lists the top-level dependencies, and the &lt;code&gt;.lock&lt;/code&gt; file stores their corresponding &lt;code&gt;transitive&lt;/code&gt; or &lt;code&gt;peer&lt;/code&gt; dependencies. Where does the actual code of the packages actually live?&lt;/p&gt;
&lt;p&gt;That&apos;s where the &lt;code&gt;node_modules&lt;/code&gt; folder comes in!&lt;/p&gt;
&lt;p&gt;Think of it as the actual &lt;strong&gt;incubator&lt;/strong&gt; of those dependencies.&lt;/p&gt;
&lt;p&gt;All the &lt;strong&gt;third-party packages&apos;s&lt;/strong&gt; codes reside there.&lt;/p&gt;
&lt;p&gt;It&apos;s also known as the black hole folder in Javascript&apos;s memes literature because it simply takes a lot of disk space.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/node-js-black-hole.png&quot; alt=&quot;Node.js as a black hole&quot; /&gt;&lt;/p&gt;
&lt;p&gt;So always double-check that it&apos;s present in your &lt;code&gt;.gitignore&lt;/code&gt; file, because you definitely don&apos;t want to push that to GitHub.&lt;/p&gt;
&lt;h2&gt;TypeScript Configuration&lt;/h2&gt;
&lt;p&gt;Now that we escaped the black hole, let&apos;s walk through these TypeScript configuration files.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;hello-world/
├── public/
├── src/
├── node_modules/
├── tsconfig.app.json
├── tsconfig.json
└── tsconfig.node.json
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each one of these files helps you to customize the TypeScript type-checking experience according to your preferences: Think of these files as the environment-specific rules of the type-checking experience offered by TypeScript.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;tsconfig.app.json&lt;/code&gt; sets the rules for your &lt;code&gt;Frontend&lt;/code&gt; or React code.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;tsconfig.node.json&lt;/code&gt; sets the rules for the &lt;code&gt;Backend&lt;/code&gt; side or the logic that runs exclusively on the server.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;tsconfig.json&lt;/code&gt; is the parent file that is read first by the ts-compiler; it holds references to the other two files.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Vite Configuration&lt;/h2&gt;
&lt;h3&gt;vite.config.ts&lt;/h3&gt;
&lt;p&gt;We&apos;ve already customized &lt;code&gt;Git&lt;/code&gt;, &lt;code&gt;TypeScript&lt;/code&gt;, and &lt;code&gt;npm&lt;/code&gt;. But what about our engine, Vite?&lt;/p&gt;
&lt;p&gt;That&apos;s where the &lt;code&gt;vite.config.ts&lt;/code&gt; file enters the game.&lt;/p&gt;
&lt;p&gt;The file simply exports a &lt;code&gt;defineConfig&lt;/code&gt; function, which receives a configuration object we can use to fine-tune how &lt;code&gt;Vite&lt;/code&gt; operates.&lt;/p&gt;
&lt;p&gt;Since &lt;code&gt;Vite&lt;/code&gt; works with most modern frameworks, we need to pass it the &lt;code&gt;React SWC plugin&lt;/code&gt; to ensure the build process is compatible with &lt;code&gt;React&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import { defineConfig } from &quot;vite&quot;;
import react from &quot;@vitejs/plugin-react-swc&quot;;

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
});
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Application Entry Point&lt;/h2&gt;
&lt;h3&gt;index.html&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;React&lt;/code&gt; is just &lt;code&gt;Javascript&lt;/code&gt;, and as you may know, &lt;code&gt;Javascript&lt;/code&gt; can&apos;t exist in the browser without &lt;code&gt;HTML&lt;/code&gt;. Similarly to how an athlete can&apos;t move his body without its bones.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;index.html&lt;/code&gt; file is the entry point of the application, it defines the main &lt;code&gt;HTML&lt;/code&gt; layout or template of all the pages that are served.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!doctype html&amp;gt;
&amp;lt;html lang=&quot;en&quot;&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;meta charset=&quot;UTF-8&quot; /&amp;gt;
    &amp;lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; href=&quot;/vite.svg&quot; /&amp;gt;
    &amp;lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&amp;gt;
    &amp;lt;title&amp;gt;Vite + TS&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;div id=&quot;root&quot;&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;script type=&quot;module&quot; src=&quot;/src/main.ts&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Inside the &lt;code&gt;&amp;lt;head/&amp;gt;&lt;/code&gt; tag we reference the &lt;code&gt;/vite.svg&lt;/code&gt; file as a &lt;code&gt;favicon&lt;/code&gt;. If you look closely, you&apos;ll see that it&apos;s located within the public folder.&lt;/p&gt;
&lt;p&gt;Any static asset (such as an image or video) stored there is publicly served. You can reference those assets from anywhere in your code using a leading slash (&lt;code&gt;/&lt;/code&gt;) followed by the path relative to the public folder.&lt;/p&gt;
&lt;h2&gt;Source Code Directory&lt;/h2&gt;
&lt;p&gt;The body of the &lt;code&gt;index.html&lt;/code&gt; contains a script tag that imports the &lt;code&gt;main.tsx&lt;/code&gt; file located within the &lt;code&gt;src&lt;/code&gt; directory.&lt;/p&gt;
&lt;h3&gt;The src folder&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;src&lt;/code&gt; folder holds all of our application&apos;s &lt;code&gt;Typescript&lt;/code&gt; code including React components, their corresponding stylesheets and other logic.&lt;/p&gt;
&lt;h3&gt;main.tsx - The React Entry Point&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;import { StrictMode } from &quot;react&quot;;
import { createRoot } from &quot;react-dom/client&quot;;
import &quot;./index.css&quot;;
import App from &quot;./App.tsx&quot;;

const divDomNode = document.getElementById(&quot;root&quot;)!
createRoot(divDomNode).render(
  &amp;lt;StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/StrictMode&amp;gt;,
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So where does all the Javascript action happen? It&apos;s &lt;code&gt;main.tsx&lt;/code&gt;. React literally binds itself to the &lt;code&gt;index.html&lt;/code&gt; here.&lt;/p&gt;
&lt;p&gt;Inside the &lt;code&gt;main.tsx&lt;/code&gt; file, we retrieve the &lt;strong&gt;DOM element&lt;/strong&gt; of the &lt;code&gt;div&lt;/code&gt; with the &lt;code&gt;id&lt;/code&gt; of &lt;code&gt;root&lt;/code&gt; using the &lt;code&gt;document.getElementById(&apos;&apos;)&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  &amp;lt;body&amp;gt;
    &amp;lt;div id=&quot;app&quot;&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;script type=&quot;module&quot; src=&quot;/src/main.tsx&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The element is passed to the &lt;code&gt;createRoot&lt;/code&gt;, a function imported from &lt;code&gt;react-dom/client&lt;/code&gt;. The function call returns the application&apos;s &lt;strong&gt;root object&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const divDomNode = document.getElementById(&quot;root&quot;)!
const applicationRootObject = createRoot(divDomNode)
 applicationRootObject.render(
  &amp;lt;StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/StrictMode&amp;gt;,
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After that, we make use of the &lt;code&gt;render&lt;/code&gt; method of the &lt;strong&gt;root object&lt;/strong&gt; to display the &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt; component -- Where an example counter component code resides.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Instead of passing &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt; directly to the render method, we wrap it in a &lt;code&gt;StrictMode&lt;/code&gt; component because it makes catching bugs easier in dev mode.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Development Server and Testing&lt;/h2&gt;
&lt;p&gt;Now that we explained briefly, how &lt;code&gt;React&lt;/code&gt; wires itself and injects the Counter example code defined inside the &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt; component inside the &lt;code&gt;&amp;lt;div/&amp;gt;&lt;/code&gt; with the id of &lt;code&gt;root&lt;/code&gt;. Let&apos;s start our app to see it happening!&lt;/p&gt;
&lt;p&gt;Let&apos;s open our terminal, type &lt;code&gt;npm or pnpm run dev&lt;/code&gt; in order to start the development server, open your browser, and then head straight to &lt;code&gt;http://localhost:5173&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Once you&apos;ve done so, you&apos;ll stumble upon this page.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/vite-server-example-page.png&quot; alt=&quot;Vite Dev Server Running&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now, in order to confirm that the &lt;code&gt;main.tsx&lt;/code&gt; file is really injecting the &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt; component inside the &lt;code&gt;div&lt;/code&gt; with the &lt;code&gt;id&lt;/code&gt; of &lt;code&gt;root&lt;/code&gt;. Let&apos;s inspect the page.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/inspect-root-div.png&quot; alt=&quot;Inspect the Root Div&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Great! All the Counter&apos;s &lt;code&gt;HTML&lt;/code&gt; code is here. And it gets even better the &lt;code&gt;Html&lt;/code&gt; is updating whenever we increment the counter. React is indeed Reacting, and we are reacting to it! Isn&apos;t that crazy?&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;There is one missing piece that we didn&apos;t cover yet in this article.&lt;/p&gt;
&lt;p&gt;Despite going through the project&apos;s files and folders and explaining how React injects the &lt;code&gt;&amp;lt;App/&amp;gt;&lt;/code&gt; component into the &lt;code&gt;&amp;lt;div/&amp;gt;&lt;/code&gt;, we haven&apos;t yet discussed what a React component actually is. We still need to explore how components are defined and why they are considered the fundamental building blocks of any &lt;code&gt;React&lt;/code&gt; application that you can see out there.&lt;/p&gt;
&lt;p&gt;Stick around for the next article, where we will address these topics in depth. Until then, Happy coding!&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/react-project-structure-explained.png" medium="image" type="image/png"/><category>react</category><category>javascript</category><category>webdev</category><enclosure url="https://sidaliassoul.com/open-graph/blog/react-project-structure-explained.png" length="0" type="image/png"/></item><item><title>Creating A React App in 2026 is EASY with Vite</title><link>https://sidaliassoul.com/blog/create-react-app-vite/</link><guid isPermaLink="true">https://sidaliassoul.com/blog/create-react-app-vite/</guid><description>Learn how to set up your development environment and create your first React application using modern tools and best practices.</description><pubDate>Wed, 15 Jan 2025 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;Getting started with &lt;code&gt;React&lt;/code&gt; is no longer as complicated as it was before.&lt;/p&gt;
&lt;p&gt;In this video, we will learn about the &lt;strong&gt;fastest&lt;/strong&gt; way to bootstrap a modern &lt;code&gt;React&lt;/code&gt; project.&lt;/p&gt;
&lt;p&gt;No, we are not going to use the deprecated &lt;strong&gt;CRA&lt;/strong&gt; or &lt;strong&gt;create-react-app&lt;/strong&gt; that has been causing pain for developers for centuries.&lt;/p&gt;
&lt;p&gt;But we will employ something called Vite, which means blazingly fast in French.&lt;/p&gt;
&lt;h2&gt;Prerequisites&lt;/h2&gt;
&lt;p&gt;So what&apos;s the only thing that stands between you and your first &lt;code&gt;React&lt;/code&gt; app? You need a runtime that lets you run &lt;code&gt;Javascript&lt;/code&gt; outside the browser -- &lt;code&gt;Node.js&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Start by heading to the official Node.js website, hit the &lt;code&gt;Get Node.js&lt;/code&gt; button, and pick your operating system, then either copy and paste the shown commands to your terminal or download the corresponding binary.&lt;/p&gt;
&lt;p&gt;After running the command or downloading the binary, let&apos;s confirm that it&apos;s indeed installed by opening our terminal, and typing&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;node --version
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If a message that looks like this appears after running the command, then congratulations, Node.js is successfully installed.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/confirm-node-js-installation.png&quot; alt=&quot;Confirm Node.js Installation&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Setting Up Vite&lt;/h2&gt;
&lt;p&gt;Now, that &lt;code&gt;Node.js&lt;/code&gt; is ready, one command is all it takes to get your entire React project up and running.&lt;/p&gt;
&lt;p&gt;Head over to the &lt;code&gt;Vite&lt;/code&gt; website, hit &lt;code&gt;get started&lt;/code&gt;, and scroll down until you find this command.&lt;/p&gt;
&lt;p&gt;This command creates your project boilerplate and installs both &lt;code&gt;Vite&lt;/code&gt; and &lt;code&gt;React&lt;/code&gt; for you. &lt;code&gt;Vite&lt;/code&gt; itself mainly handles two things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;It serves your code during development while offering features such as Hot reload.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It bundles your JavaScript, HTML and other assets together when you&apos;re ready for production.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/create-vite-project-command.png&quot; alt=&quot;Command to Install Vite&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Node.js&lt;/code&gt; comes with &lt;code&gt;npm&lt;/code&gt; out of the box – a package manager that installs your project dependencies. But I personally use &lt;code&gt;pnpm&lt;/code&gt; instead, and here&apos;s why it&apos;s better:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;It caches your dependencies globally.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;It reuses them across projects.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That makes everything way faster and more economical, especially if you use mobile data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm create vite@latest
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So you can either copy this npm command and run it straight away or install pnpm globally:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install -g pnpm
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In case you&apos;ve gone the &lt;code&gt;pnpm&lt;/code&gt; path and installed it globally, you just have to replace &lt;code&gt;npm&lt;/code&gt; with &lt;code&gt;pnpm&lt;/code&gt; in the previous command.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm create vite@latest
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Project Configuration&lt;/h2&gt;
&lt;p&gt;Now that we&apos;ve run the command, &lt;code&gt;Vite-cli&lt;/code&gt; is going to walk you through a quick setup.&lt;/p&gt;
&lt;p&gt;Let&apos;s go with &lt;code&gt;hello-world&lt;/code&gt; as a project name.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/choose-vite-project-name.png&quot; alt=&quot;Vite CLI prompting the user to choose a project name&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Since we are building a React app, let&apos;s select &lt;code&gt;React&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/vite-cli-choose-framework.png&quot; alt=&quot;Vite CLI prompting the user to choose a framework&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Now it&apos;s asking us to choose between JavaScript or TypeScript. Honestly, I prefer TypeScript because its static typing improves IDE autocompletions and makes the developer experience much smoother.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/courses/vite-cli-choose-ts-or-js.png&quot; alt=&quot;Vite CLI prompting the user to choose Javascript or Typescript&quot; /&gt;&lt;/p&gt;
&lt;p&gt;You might be wondering about what &lt;code&gt;SWC&lt;/code&gt; even is. It&apos;s a &lt;strong&gt;blazingly fast compiler&lt;/strong&gt; that will speed up your development experience by almost 20X. Nobody hates speed, so let&apos;s select &lt;code&gt;Typescript + SWC&lt;/code&gt; and hit enter.&lt;/p&gt;
&lt;p&gt;Let&apos;s just skip the two remaining options.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;/assets/Screenshot%202026-02-24%20at%2010.37.47%E2%80%AFAM.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;h2&gt;Installing Dependencies&lt;/h2&gt;
&lt;p&gt;The moment you hit enter, &lt;code&gt;Vite-Cli&lt;/code&gt; creates your project.&lt;/p&gt;
&lt;p&gt;As soon as it&apos;s done, navigate to it by typing &lt;code&gt;cd hello-world&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;After that, install the dependencies by running &lt;strong&gt;&quot;npm install&quot;&lt;/strong&gt; or &lt;strong&gt;&quot;pnpm install&quot;&lt;/strong&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install
# Or
pnpm install
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Running The Development Server&lt;/h2&gt;
&lt;p&gt;Once the installation is done, let&apos;s run the following command.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;pnpm run dev
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The latter will start the development server on &lt;code&gt;http://localhost:5173&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Just click on this URL while holding Ctrl or just copy-paste it into the browser.&lt;/p&gt;
&lt;p&gt;Finally, your project is ready.&lt;/p&gt;
&lt;p&gt;Open it using your preferred IDE, go into the &lt;code&gt;App.tsx&lt;/code&gt; file located within the &lt;code&gt;src&lt;/code&gt; folder, change something there, and voilà, the change is reflected instantly on the web page.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;So this is all it takes to get your project up and running with &lt;code&gt;VITE&lt;/code&gt;, LITERALLY, one single command!&lt;/p&gt;
&lt;p&gt;But looking at this file tree might be a source of anxiety, right?&lt;/p&gt;
&lt;p&gt;So instead of blowing everything, we must understand the generated boilerplate code.&lt;/p&gt;
&lt;p&gt;In the next article of the series, we are going to explore every file and folder of this intimidating Halloween tree.&lt;/p&gt;
&lt;p&gt;Until then... happy coding!&lt;/p&gt;
</content:encoded><media:content url="https://sidaliassoul.com/open-graph/blog/create-react-app-vite.png" medium="image" type="image/png"/><category>react</category><category>tutorial</category><category>tooling</category><enclosure url="https://sidaliassoul.com/open-graph/blog/create-react-app-vite.png" length="0" type="image/png"/></item></channel></rss>