<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>NotJustCoders - Engineering Insights</title><description>Deep dives into software engineering, system design, and the art of problem-solving. A curated learning hub for engineers and problem solvers.</description><link>https://notjustcoders.com/</link><language>en-us</language><item><title>Creating A React App in 2026 is EASY with Vite</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/create-react-app-vite/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

Getting started with `React` is no longer as complicated as it was before.

In this video, we will learn about the **fastest** way to bootstrap a modern `React` project.

No, we are not going to use the deprecated **CRA** or **create-react-app** that has been causing pain for developers for centuries.

But we will employ something called Vite, which means blazingly fast in French.

## Prerequisites

So What&apos;s the only thing that stands between you and your first `React` app? You need a runtime that lets you run `Javascript` outside the browser -- `Node.js`.

Start by heading to the official Node.js website, hit the `Get Node.js` button, and pick your operating system–either copy and paste the shown commands to your terminal or just download the corresponding binary.

After running the command or downloading the binary, let&apos;s confirm that it&apos;s indeed installed by opening our terminal, and typing

```bash
node --version
```

If a message that looks like this appears after running the command, then congratulations—Node.js is successfully installed.

![Confirm Node.js Installation](/assets/courses/confirm-node-js-installation.png)

## Setting Up Vite

Now, that `Node.js` is ready, one command is all it takes to get your entire React project up and running.

Head over to the `Vite` website, hit `get started`, and scroll down until you find this command.

This command creates your project boilerplate and installs both `Vite` and `React` for you. `Vite` itself mainly handles two things:

*   It serves your code during development while offering features such as Hot reload.
    
*   It bundles your JavaScript, HTML and other assets together when you&apos;re ready for production.
    

![Command to Install Vite](/assets/courses/create-vite-project-command.png)

`Node.js` comes with `npm` out of the box – a package manager that installs your project dependencies. But I personally use `pnpm` instead, and here&apos;s why it&apos;s better:

*   It caches your dependencies globally.
    
*   It reuses them across projects.
    

That makes everything way faster and more economical, especially if you use mobile data.

```bash
npm create vite@latest
```

So you can either copy this npm command and run it straight away or install pnpm globally:

```bash
npm install -g pnpm
```

In case you&apos;ve gone the `pnpm` path and installed it globally, you just have to replace `npm` with `pnpm` in the previous command.

```bash
pnpm create vite@latest
```

## Project Configuration

Now that we&apos;ve run the command, `Vite-cli` is going to walk you through a quick setup.

Let&apos;s go with `hello-world` as a project name.

![Vite CLI prompting the user to choose a project name](/assets/courses/choose-vite-project-name.png)

Since we are building a React app, let&apos;s select `React`.

![Vite CLI prompting the user to choose a framework](/assets/courses/vite-cli-choose-framework.png)

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.

![Vite CLI prompting the user to choose Javascript or Typescript](/assets/courses/vite-cli-choose-ts-or-js.png)

You might be wondering about what `SWC` even is. It&apos;s a **blazingly fast compiler** that will speed up your development experience by almost 20X. Nobody hates speed, so let&apos;s select `Typescript + SWC` and hit enter.

Let&apos;s just skip the two remaining options.

![](/assets/Screenshot%202026-02-24%20at%2010.37.47%E2%80%AFAM.png)

## Installing Dependencies

The moment you hit enter, `Vite-Cli` creates your project.

As soon as it&apos;s done, navigate to it by typing `cd hello-world`.

After that, install the dependencies by running **&quot;npm install&quot;** or **&quot;pnpm install&quot;**.

```bash
npm install
# Or
pnpm install
```

## Running The Development Server

Once the installation is done, let&apos;s run the following command.

```bash
pnpm run dev
```

The latter will start the development server on `http://localhost:5173`.

Just click on this URL while holding Ctrl or just copy-paste it into the browser.

Finally, your project is ready.

Open it using your preferred IDE, go into the `App.tsx` file located within the `src` folder, change something there, and voilà, the change is reflected instantly on the web page.

## Conclusion

So this is all it takes to get your project up and running with `VITE`, LITERALLY, one single command!

But looking at this file tree might be a source of anxiety, right?

So instead of blowing everything, we must understand the generated boilerplate code.

In the next article of the series, we are going to explore every file and folder of this intimidating Halloween tree.

Until then... happy coding!</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>beginner</category><category>tutorial</category><author>sid-ali-assoul</author></item><item><title>Creating Your First React Component is EASY</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/first-react-component-tutorial/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/first-react-component-tutorial/</guid><description>Learn how to create and use React components, the building blocks of any React application.</description><pubDate>Wed, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

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?

```bash
pnpm create vite@latest
# Or
npm create vite@latest
```

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.

```
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
```

In this article, you&apos;ll learn all you need to know about creating React components.

Without any further ado let&apos;s dive in.

## Creating Your First React Component

Now that we&apos;ve initialized our **Vite** project, let&apos;s jump over to the **App.tsx** file, located within the **src** directory.

Once you&apos;ve done so, you&apos;ll notice that **Vite** comes with a predefined counter-example.

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.

```tsx
function App() {
  const [count, setCount] = useState(0);
  return (
    &lt;&gt;
      {/** more code here ... */}
      &lt;div className=&quot;card&quot;&gt;
        &lt;button onClick={() =&gt; setCount((count) =&gt; count + 1)}&gt;
          count is {count}
        &lt;/button&gt;
      &lt;/div&gt;
      {/** more code here ... */}
    &lt;/&gt;
  );
}
```

## Simplifying the App Component

Let&apos;s simplify this code by deleting everything inside the **App** function and making it return a simple container **div** that wraps an **h1** header and an unordered list **ol** with a few random list elements `li`.

```typescript
function App(){
  return (
    &lt;div&gt;
      &lt;h1&gt;This is my first react component&lt;/h1&gt;
      &lt;ol&gt;
        &lt;li&gt;Wake up&lt;/li&gt;
        &lt;li&gt;Code&lt;/li&gt;
        &lt;li&gt;Eat&lt;/li&gt;
        &lt;li&gt;Sleep&lt;/li&gt;
        &lt;li&gt;Repeat&lt;/li&gt;
      &lt;/ol&gt;
    &lt;/div&gt;
  );
}
```

## Creating a New Image Component

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?

As we said before, it&apos;s a matter of wrapping your HTML in a function.

Let&apos;s place it just above the App component. The component returns an img HTML tag with the following attributes:

*   An alt attribute to support screen readers.
    
*   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.
    

```typescript
function Image(){
  return &lt;img alt=&quot;Blog post image&quot; src=&quot;https://picsum.photos/500/400&quot; /&gt;;
}
```

&gt; We didn&apos;t have to use the parentheses in the `Image` component because the returned code is only written in a single line, in contrast with the `App` component where we had to use parentheses because the code spanned **more than one line**.

## Using the Image Component in App

Next, let&apos;s use it in `App`. 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;Image/&gt;`.

```tsx
function Image() {
  return &lt;img alt=&quot;Blog post image&quot; src=&quot;https://picsum.photos/500/400&quot; /&gt;;
}
function App() {
  return (
    &lt;div&gt;
      &lt;h1&gt;This is my first react component&lt;/h1&gt;
      &lt;Image /&gt;
      &lt;ol&gt;
        &lt;li&gt;Wake up&lt;/li&gt;
        &lt;li&gt;Code&lt;/li&gt;
        &lt;li&gt;Eat&lt;/li&gt;
        &lt;li&gt;Sleep&lt;/li&gt;
        &lt;li&gt;Repeat&lt;/li&gt;
      &lt;/ol&gt;
    &lt;/div&gt;
  );
}
```

## Running the Development Server

The code is ready; all that remains is to start the development server by running the following:

```bash
pnpm run dev
# or
npm run dev
```

Subsequently, we need to head into `http://localhost:5173` and inspect the page.

![First component preview](/assets/courses/inspect-content-vite-first-component.png)

React injects the final HTML into a div known as the root div.

As you can see, the HTML that is returned by the **App** component and its child `Image` component got merged together and then injected inside the `root` `div`.

![First component root div preview](/assets/courses/first-component-root-div-content.png)

## Organizing Components into Separate Files

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.

So let&apos;s create a `image.tsx` file at the same directory level as **app.tsx**, then just copy the **Image function** declaration into its own dedicated file.

Every file in `Javascript` is considered its own closed module. So anything that is declared there is not accessible unless we explicitly export it.

## Exporting Components

There are two ways to export our component:

1.  We can add the export keyword next to it, and then import it in `app.tsx` like this:
    

`image.tsx` file:

```typescript
export Image;
```

`app.tsx` file:

```typescript
import { Image } from &quot;./image.tsx&quot;;
```

This approach is called normal exporting; a file can have many normal exports.

```
import {C1, C2 , C3} from &quot;file.tsx&quot;
```

2.  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.
    

`image.tsx` file:

```typescript
export default Image;
```

`app.tsx` file:

```typescript
import Image from &quot;./image.tsx&quot;;
```

As the name implies, a file can only have a single default export.

## Bonus Performance Information

Before moving on, there is one common mistake that can silently kill your app&apos;s performance: **never declare a component inside another component.**

Doing this forces **React** to treat the inner component as &quot;brand new&quot; on every single update. This destroys any chance of caching or optimization, leading to potentiel performance issues.

```tsx
export function App(){
  // ❌
  function SubComponent(){
    return (
      &lt;div&gt;{/* code... */}&lt;/div&gt;
    )
  }
  return ( /*code...*/);
}
```

`Html` Files can get really big, and just making sure that tags are closing properly is honestly a big drag.

`React` takes a modular approach by dividing the problem of building complex **interactive web pages** into smaller **sub-problems** or **building blocks** known as `components`.

## Conclusion

But there&apos;s an important point that we avoided talking about during this article.

Can you guess? -- Yes, that&apos;s right; we kept saying &quot;HTML-like code.&quot; But we never explained why.

Well, because that&apos;s not HTML code; it&apos;s actually a syntax extension of JavaScript, and it&apos;s called JSX!

In the next article of the series, we will reveal **more secrets** 🤫 about this mystery. Until then, happy coding.</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>beginner</category><category>tutorial</category><author>sid-ali-assoul</author></item><item><title>Master JSX in 8 Minutes (Before You Write Your Next React Component) -- React Tutorial</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/jsx-tutorial-react-javascript-guide/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

So what the heck is JSX? And what does it have to do with HTML?

`JSX` is a syntax extension for `JavaScript`. Yes, you heard it right—it&apos;s an extension of `JavaScript` not `HTML`, despite what many people think. This means that `JSX` is eventually converted into valid `JavaScript` code 😮.

Under the hood, the conversion is handled by compilers like `Babel` or `SWC`. Consequently, the entire component tree representing our `App` is transformed into `JavaScript`. These objects are understood by the browser and used by the `React` runtime to render the final `HTML` code.

For example, the code below.

```typescript
function Image() {
  return &lt;img alt=&quot;Blog post image&quot; src=&quot;https://picsum.photos/500/400&quot; /&gt;;
}

function App(){
    return (
        &lt;Image/&gt;
    )
}
```

...will be converted by `Babel` or `SWC` into this:

```typescript
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, {});
}
```

&gt; The `__jsx` is imported from the `react/jsx-runtime`;it&apos;s used to build and return the object representing the `JSX` node.

We use `JSX` for its conciseness. It&apos;s easier to read and write because it closely resembles the final `HTML` that will be shipped to the user&apos;s browser.

In this article, we will walk through everything you need to know about `JSX` including:

*   The specific syntax rules that distinguish it from `HTML`.
    
*   How to embed `JavaScript` using the curly brace syntax.
    

## JSX vs HTML: Key Differences

At first glance, `JSX` looks like `HTML`. In reality, its strictness may easily break your code if you&apos;re not careful.

So the first rule, is simple—just be strict with your tags and you&apos;ll be fine

The rule consists of always closing tags, including self-closing ones like `&lt;img/&gt;` or wrapping tags like `&lt;div&gt;`s.

```tsx
function App(){
 return (
   &lt;div&gt; // ✅

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

   &lt;/div&gt; // ✅
 )
}
```

In addition to being strict with the tags themselves, `JSX` also has some special rules regarding their attributes-- Instead of kabab-case in `HTML`, you must use camel case when defining attributes.

```tsx
&lt;button tab-index={0}&gt; &lt;/button&gt;  // Kabab case ❌
&lt;button tabIndex={0}&gt; &lt;/button&gt;  // Camel case ✅
```

Note that `JavaScript`&apos;s reserved keywords are not allowed as attribute names. As an example of that, the `class` keyword that is used to define classes is not allowed. That&apos;s why you need to use `className` instead.

As bonus information, there is one exception to the above rule, which is attributes that start with either `data-*` or `area-*`.

```tsx
&lt;div class=&quot;...&quot;&gt; &lt;/div&gt;  // ❌
&lt;div className=&quot;...&quot;&gt; &lt;/div&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!

```tsx
function my_component() {
  /*...*/
} // Snake case ❌
function MyComponent() {
  /*...*/
} // Camel case ✅
```

Now, let me ask you a question, can a `JavaScript` function return multiples objects without wrapping them in an array or a parent object?-- No that&apos;s a syntax error right?

```typescript
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; }]; // ✅
}
```

Using a `div` as a wrapper can be annoying sometimes, especially when styling elements. Instead, there is a built-in `React` component that literally does nothing but virtually wrapping its children without even showing in the browser `DOM`.

You can use it this way. Or more concisely using empty tags `&lt;&gt;&lt;/&gt;`

```tsx
import React from &apos;react&apos;
function CorrectComponent1(){ // ✅
  return (
    &lt;React.Fragment&gt;
      &lt;h1&gt;Title&lt;/h1&gt;
      &lt;div&gt;Description &lt;/div&gt;
    &lt;/React.Fragment&gt;
  )

// Or more concisely

function CorrectComponent2(){ // ✅
  return (
    &lt;&gt;
      &lt;h1&gt;Title&lt;/h1&gt;
      &lt;div&gt;Description &lt;/div&gt;
    &lt;/&gt;
  )
```

## Using JavaScript in JSX

Sure we can perform any kind of `JavaScript` logic in the function&apos;s body before returning the `JSX` including if statements, for loops and so on.

But is there a built-in way to use `JavaScript` or reference a `JavaScript` value or object from within the `JSX` code itself?

Yes, and it&apos;s pretty simple; just use the curly bracket syntax `{}` and then reference any variable, value, function call, or any expression from the `JavaScript world 🌎`.

Rather than hardcoding the title value in the `Markup` here, we can store the `h1` tag&apos;s inner content in a `JavaScript` variable as a string.

And then reference it in the `Markup`, using the curly bracket syntax like this.

```typescript
function App(){
  const title = &quot;This is my first react component&quot;;

  return (
    &lt;div&gt;
      &lt;h1&gt;{title}&lt;/h1&gt;
      &lt;ol&gt;
        &lt;li&gt;Wake up&lt;/li&gt;
        &lt;li&gt;Code&lt;/li&gt;
        &lt;li&gt;Eat&lt;/li&gt;
        &lt;li&gt;Sleep&lt;/li&gt;
        &lt;li&gt;Repeat&lt;/li&gt;
      &lt;/ol&gt;
    &lt;/div&gt;
  );
}
```

Think of the curly braces as a return statement. Anything that returns a string or `JSX` code can be used inside them.

Including functions.

```typescript
function App(){
  const title = &quot;This is my first react component&quot;;
  const createTitle = (title) =&gt; &lt;h1&gt;{title}&lt;/h1&gt;;

  return (
    &lt;div&gt;
      {createTitle(title)}
      &lt;ol&gt;
        &lt;li&gt;Wake up&lt;/li&gt;
        &lt;li&gt;Code&lt;/li&gt;
        &lt;li&gt;Eat&lt;/li&gt;
        &lt;li&gt;Sleep&lt;/li&gt;
        &lt;li&gt;Repeat&lt;/li&gt;
      &lt;/ol&gt;
    &lt;/div&gt;
  );
}
```

And variables.

```typescript
const var1 = &lt;h1&gt;This is my first react component&lt;/h1&gt;;
const var2 = (
  &lt;div&gt;
    {var1}
    &lt;ol&gt;
      &lt;li&gt;Wake up&lt;/li&gt;
      &lt;li&gt;Code&lt;/li&gt;
      &lt;li&gt;Eat&lt;/li&gt;
      &lt;li&gt;Sleep&lt;/li&gt;
      &lt;li&gt;Repeat&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/div&gt;
);
```

Beware of using if statements or loops inside the `JSX`. Only values, variables and expressions are allowed!

```tsx
return (
if(true){   ❌



}else{

}

for (){}  ❌

while(){} ❌


)
```

Is it possible to reference attributes and styles?

All attributes except `style` can be set to strings, using the curly braces syntax.

```tsx
function App(){

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

    return(
    &lt;&gt;
      &lt;div className={className}&gt;&lt;/div&gt;
      &lt;/&gt;
    )
}
```

In standard `HTML` we set the `style` attribute as a string that looks like this;

```tsx
&lt;div style=&quot;background-color:black; color:pink&quot;/&gt;
```

But things are a bit different, in the `JSX` realm.

We need to pass an object, that includes your `CSS` properties and values as key-value pairs. Such as the keys are written in camel case instead kabab case.

```css
/* CSS kebab-case */
background-color: black;
color: pink;
```

```tsx
function App(){

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

    return(
      &lt;div style={style}/&gt;
    )
}
```

Often people get tripped up by these double curly braces `{{}}`. They think that it&apos;s a special `JSX` syntax. But it&apos;s actually just a regular JavaScript object being passed inside the curly brackets.

```jsx
&lt;img style={{ backgroundColor: &quot;red&quot; }} /&gt;
```

```tsx
function App() {
  const styleObj = { backgroundColor: &quot;red&quot; };

  return (
    &lt;img style={styleObj} /&gt; // Instead of style={{backgroundColor:&apos;red&apos;}}
  );
}
```

Congratulations! You&apos;ve just earned a new badge: JSX Syntax Wizard! Now that you learned how the `JSX` magic works under the hood and gone through its spell book. You&apos;re officially ready to write clean, error-free React components.

## Conclusion

But here&apos;s the catch: a Button component is practically useless if you can&apos;t reuse it with different titles, Right?

We need some sort of mechanism that allows us to pass data to a React component in order to make it `generic` and `reusable`.

In other words, we need to be able to pass a `title` argument to the Button component!

That&apos;s exactly what we are going to explore in the next article: we will learn about component arguments, also known as Props.

Until then... happy coding.</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>beginner</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>Master Conditional Rendering in React: If Statements, Ternaries, &amp; Logical &amp;&amp;</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-conditional-rendering-guide/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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>## Introduction

A **React** component is a **building block** that runs **JavaScript logic** and then returns the UI code in a special **HTML-like** syntax known as **JSX**.

Some **UI** elements like **dropdowns**, **navbars,** and so on need to **display different things** depending on **different conditions**.

In a **React** component there are two different ways to conditionally render the **UI:**

1.  The first one is using **if** statements directly in the function&apos;s body and returning different **JSX** codes depending on the **conditions**.
    
2.  The second approach consists of directly **embedding the conditions in the** **JSX** code within the **curly braces** **{} syntax**.
    

In this article, we&apos;re going to explore both cases and master **JSX** conditional rendering.

## Conditional Rendering with If Statements

With these core concepts in mind, let&apos;s look at a practical example where an **emoji component** receives a **&quot;type&quot;** input prop that can be either **&quot;angry&quot;** or **&quot;smile**.&quot;

The corresponding **emoji** gets rendered depending on the value of **&quot;type.&quot;**

We have **two ways** of achieving this in **React**:

Right in the emoji component&apos;s body, we can use a **branching control flow statement** such as an **&quot;if&quot;** or &quot;**switch case&quot;** to return the right **emoji&apos;s** **JSX** code depending on the value of **&quot;type.&quot;**

```tsx
function Emoji({type}: {type: &apos;angry&apos; | &apos;smile&apos;}) {
  if(type === &apos;angry&apos;) {  
    return (
      &lt;div&gt;....&lt;/div&gt;
    );
  } else if (type === &apos;sad&apos;) {
    return &lt;div&gt;,....&lt;/div&gt;;
  } else {
    console.warn(&quot;An invalid type prop was passed to Emoji component&quot;);
    return null;
  }
}

function App() {
  return (
    &lt;div style={{display: &apos;flex&apos;, gap: &apos;20px&apos;}}&gt;
      &lt;Emoji type=&quot;angry&quot; /&gt;
      &lt;Emoji type=&quot;sad&quot; /&gt;
    &lt;/div&gt;
  );
}
```

And then inside the **app** component, we can **call the component multiple times** while passing **different values** to the **&quot;type&quot;** prop.

That&apos;s nice and all, but imagine if we needed to update the style of one **&quot;div.&quot;** With the current setup, we would have to add the styles to every if-statement branch, which is **repetitive** and **inconvenient.**

One solution for that is to store the emoji in a **shared local variable,** and then depending on the **type** prop value, we assign the corresponding emoji.

After that we can wrap the value stored in the variable in a **common shared &quot;div.&quot;**

```tsx
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 &lt;&gt;Wrong emoji type&lt;/&gt;;
  }
  return &lt;div style=&quot;&quot;&gt;{emoji}&lt;/div&gt;;
}
```

That was conditional rendering in the **JavaScript** **land**; let&apos;s now explore conditionally displaying elements **directly inside** the `JSX` code.

## Conditional Rendering in JSX

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?

Well, if you&apos;re thinking about an **if statement, then** the answer is wrong, because as the name implies, it&apos;s a statement. In other words, it does not return anything.

Fortunately, 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!

```typescript
condition ? exprIfTrue : exprIfFalse;
```

&gt; You can read it as: **if** some condition is **true** (**question mark**) **return** this expression **else** (**colon**) return this alternative expression.

For example, let&apos;s say that we want to know the user&apos;s **age category** and then store it in a variable; we can use a **ternary operator,** which reads as follows: **If age is greater than or equal to 18, return &quot;adult&quot;; otherwise, return &quot;minor.&quot;**

```typescript
const userAgeCategory = age &gt;= 18 ? &quot;adult&quot; : &quot;minor&quot;;
```

Using the ternary operator inside **JSX** will save us from the burden of creating a **shared local variable** as we did previously or duplicating the styles everywhere. Therefore, making the component more maintainable.

```tsx
function Emoji({type}: {type: &apos;angry&apos; | &apos;smile&apos;}) {
  return &lt;div style=&quot;&quot;&gt;{type === &apos;angry&apos; ? &quot;...&quot; : &quot;...&quot;}&lt;/div&gt;;
}
```

## Using the Logical AND Operator

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.

Let&apos;s say that we&apos;ve got an **isUserLoggedIn** **boolean** variable, and we want to display the **emojis** list only **when the user is logged in**.

We can easily do that with the **ternary operator by** displaying the emoji list when the `isLoggedIn` variable is set to it `true` and returning `null` when it&apos;s not.

```tsx
isLoggedIn ? () : null
```

Setting **&quot;null&quot;** like that sounds verbose, right? Let&apos;s make it more concise by using the **&quot;&amp;&amp;&quot;** operator to only render the list when the **isLoggedIn** variable gets evaluated to **&quot;true.&quot;** By default **JavaScript** ignores the second side of an **and** operator if the first side is set to **&quot;false.&quot;**

&gt; Note that we should only use the **&amp;&amp;** operator when we&apos;re absolutely sure that the left hand side of the expression is not a number.

&gt; A common mistake is to use a **number** as the condition, that works for most of the cases because **Javascript** will automatically convert any type used there into a **boolean** but if it&apos;s of a number type and its value is equal to **0**. JavaScript will treat it as if it&apos;s equal a **&quot;0&quot;** string.

![Zero Hi Javascript Meme](/assets/courses/zero-hi-javascript-meme.jpg)

&gt; To fix that we can either add the negation operator &quot;**!&quot;** two times just before the **number** or convert the number into a condition by **comparing it with another** **&quot;Number&quot;** – For example we can compare the age variable with 18: **&quot;age &gt;= 18&quot;**.

## Conclusion

So with conditional rendering, we can make a **React** component display different things depending on a bunch of conditions. Those conditions are either defined on the **&quot;JavaScript Logic&quot;** side just before rendering the **JSX** or are directly embedded **in the JSX markup**.

While conditional rendering allows us to make decisions about what component should be rendered, it is not sufficient alone to deal with real-world data.

Real-world data often comes in collections of items such as an array of products, customers, and so on. So what are the missing constructs that we need to master to avoid repeating ourselves when deleting such cases?

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 is not meant for making decisions but for not repeating ourselves. Yes, we are talking about loops in React.

Until then, happy coding.</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>intermediate</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>React Event Handlers Tutorial: Complete Guide to onClick and Event Handling</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-event-handlers-onclick-tutorial/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

A **button** is meant to be **clicked**, and when it&apos;s clicked, we **instinctively** expect something to happen. right?

Well, the thing that will happen is **defined by you, the developer,** as a **JavaScript** function doing something; let&apos;s say displaying an alert message as an example.

**The function whose job is to respond to an event triggered by something like a user interaction such as clicking** is called an **event handler**, and it&apos;s a normal **JavaScript** function declared within the component. This special function can be attached to any **JSX** element such as **buttons**, **divs**, **inputs,** and so on.

In this article, **we will dive deeper into event handlers** while **exploring important concepts** that every developer needs to master, such as:

*   Passing event handlers between **React** components.
    
*   **Event propagation** and why understanding it is so important.
    
*   And finally, how to stop event propagation and other browser default behaviors when needed.
    

So if that sounds interesting let&apos;s dive in.

## Event Handlers Basics

**React** makes attaching an event handler to a **JSX** element really straightforward.

Let&apos;s say that we&apos;ve got a component rendering a **button** named **&quot;click me.&quot;** Let&apos;s define an **event handler** named **&quot;handleClick&quot;** as a locally declared function within the component as we&apos;ve discussed previously.

Usually, the **React** community follows the naming convention that cons**i**sts of **starting the event handler&apos;s name with &quot;handle&quot; followed by the event name**. Some examples of that include **handleClick**, **handleHover**, **handleFocus,** and so on.

Now, we just have to assign the event handler (aka our locally declared function) to a special type of **prop** starting with **&quot;on&quot;** and then followed by the name of the event, such as **onClick**, **onFocus**, **onHover,** and so on. In our case let&apos;s pass it to onClick.

A mistake that&apos;s often repeated by most beginners is calling the function instead of just assigning the function name.

```tsx
function Button(){

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

}
return (
    &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt; {/* ✅ */}
    {/* &lt;button onClick={handleClick()} /&gt;Click me &lt;/button&gt; ❌ */ }
)
}
```

Doing so will just **make the function run at every single render or component update,** which is obviously not our goal here.

The function that is attached to the **onClick** prop is going to get called. Consequently, the alert message will pop up only when the **button** gets clicked by the user.

What if our component receives a **username** prop? Can we access it in the **event handler**?

```tsx
function Button({username}){

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

}
return (
    &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt; {/* ✅ */}
)
}
```

Yes, actually that&apos;s one of the advantages of declaring an **event handler** within the component. Doing so allows the **event handler** to access its **parent&apos;s outer scope variables or functions,** such as **props** or any other stuff.

### Passing Event Handlers as Props

Okay, now what if you wanted to use the **Button** component in multiple places?

Declaring &quot;**handleClick**&quot; inside it makes it impossible to change the **button&apos;s component&apos;s** primary behavior, which is reacting to different events differently depending on where it&apos;s used. Therefore, it becomes less reusable.

So can we solve this with props? In addition to that, is it even possible to pass functions as props?

Functions are first-class citizens in **JavaScript**. Consequently, they can be passed to other functions, therefore, **React** components. So it&apos;s obviously possible to do that.

Now let&apos;s make our Button component accept a new prop called **&quot;onClick,&quot;** assign it to the button&apos;s &quot;**onClick&quot;** prop, and then declare a **handleClick** event handler inside the parent component itself. And then pass it to the **Button** child component.

```tsx
function Button({username,onClick}){

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

function App(){

const username = &quot;Sid Ali&quot;

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

}

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

  )
}
```

&gt; By convention **event handler props** are named exactly as the **JSX** elements **built-in** **events props**.
&gt; 
&gt; So they should start with **on** followed by either the event name or the interaction that need to be performed such as **onClick**, **OnUploadFile**, **onTryingToFindARandomName** and so on.

## Event Propagation and Bubbling

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 **event bubbling or propagation**.

But before that, let me ask you a simple question.

What will happen if you have clicked on the child component of two nested **JSX** elements, both having an event attached to their **onClick** prop? Which component will show its corresponding alert message?

```tsx
function Parent(){
  return (
    &lt;div onClick={()=&gt;alert(&quot;Hello From Parent&quot;)}&gt;
      &lt;Child1 /&gt;
    &lt;/div&gt;
  )
}

function Child(){
  return (
    &lt;button onClick={()=&gt;alert(&quot;Hello from Child&quot;)}&gt;Click me&lt;/button&gt;
  )
}
```

```
-&gt; (1) Hello from Child
-&gt; (2) Hello from Parent 
```

The answer, as you may have guessed, is both but in a special order.

The alert message corresponding to the **child** component will get displayed first, and then the **parent** will follow after that.

We call what has just happened **event propagation or bubbling**. We say that **the click event has propagated from the child to the parent**.

### Stopping Event Propagation

If you happen to be bothered by such default behavior, you can stop the propagation by doing as follows:

```tsx
function Child(){
  return (
    &lt;button onClick={(e)=&gt;{
      e.stopPropagation()
      alert(&quot;Hello from Child&quot;)}
      }&gt;Click me&lt;/button&gt;
  )
}
```

&gt; Every **event handler** has access to an optional **e** argument which is a shorthand standing for **event.** You can use this argument to either read information about the **event** or perform actions on it.

Among those actions is being able to call the **stopPropagation** method to prevent the event from **bubbling up** to **its parent**.

### Alternative to Propagation

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.

You can achieve that by **passing the parent&apos;s event handler as a prop and then calling it after stopping the propagation and running some code**.

```tsx
function Parent(){
  function handleClick(){
    alert(&quot;Hello From Parent&quot;)
  }
  return (
    &lt;div onClick={handleClick}&gt;
      &lt;Child1  onClick={handleClick}/&gt;
    &lt;/div&gt;
  )
}

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

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

    }}&gt;Click me&lt;/button&gt;
  )
}
```

```
-&gt; (1) Hello from Child
-&gt; (2) Hello from Parent 
```

## Preventing Default Browser Behavior

In addition to propagation, there is another annoying event that you will definitely want to prevent.

When you submit a form, by default the browser refreshes the page, therefore killing your entire **React** application and probably causing some side effects, like smashing your keyboard from anger when that happens.

```tsx
function Form(){

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

  return (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;button&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  )
}
```

![Browser Refresh Meme](/assets/courses/browser-refresh-meme.jpg)

So similarly to what we did to stop the propagation. All you need to do here is to go to the form&apos;s **onSubmit**\-attached event handler, make sure to define the **event parameter e**, and then call the **preventDefault** method on the **e** object to **prevent the default browser refresh behavior**.

```tsx
function Form(){

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

  return (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;button&gt;Submit&lt;/button&gt;
    &lt;/form&gt;
  )
}
```

## Conclusion

Events are happening all the time in a **highly interactive web application**.

But when an event fires, it&apos;s usually handled by modifying some components in the **React** 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

In the next article of the series, we will finally explore how React **reacts** and **remembers** what has happened now and in the past after some series of interactions or events.

Until then, happy coding!</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>intermediate</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>Just Created Your React Project? Don&apos;t PANIC—here&apos;s every file explained</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-project-structure-explained/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>You just created your first React project. Hopefully using `Vite`

```
npm create vite@latest
```

But you stumbled upon a bunch of weird files and folders.

So you started clicking around, trying to connect the dots, but the more files you opened, the more lost you felt.

We&apos;re going to break down every single file, one by one, while building a mental map of how they connect.

## Project Structure Overview

At first glance we can see:

*   Three main folders `src`, `public` and `node_modules`.
    
*   Various config files that we can edit to customize our project.
    

```
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
```

## Configuration Files

### .gitignore

The `.gitignore` configuration file is used to tell Git which files and directories should be ignored when staging or committing your changes.

```bash
# All the directories or files listed below will be ignored by git
node_modules
dist
dist-ssr
*.local
```

### package.json

So what about the `package.json` file?

Picture it this way: it&apos;s like a library&apos;s index—it lists all the top-level dependencies of the project.

As any package that you install may also have its own dependencies, which are known as `peer` or `transitive` dependencies

A `.lock` file is constantly managed and updated by your chosen package manager.

In fact, it&apos;s automatically updated every time you install dependencies by running either

```bash
npm install
```

or

```bash
npm install &lt;package-name&gt;
```

```json
{
  &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; 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;
  }
}
```

In addition to listing top-level dependencies, the `package.json` file also exposes scripts, which are commands that you can run on the terminal, such as:

*   `npm run dev` which starts the development server
    
*   `npm run build` which generates the production-ready bundle.
    

### node\_modules

So if the `package.json` file only lists the top-level dependencies, and the `.lock` file stores their corresponding `transitive` or `peer` dependencies. Where does the actual code of the packages actually live?

That&apos;s where the `node_modules` folder comes in!

Think of it as the actual **incubator** of those dependencies.

All the **third-party packages&apos;s** codes reside there.

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.

![Node.js as a black hole](/assets/courses/node-js-black-hole.png)

So always double-check that it&apos;s present in your `.gitignore` file—you definitely don&apos;t want to push that to GitHub.

## TypeScript Configuration

Now that we escaped the black hole, let&apos;s walk through these TypeScript configuration files.

```
hello-world/
├── public/
├── src/
├── node_modules/
├── tsconfig.app.json
├── tsconfig.json
└── tsconfig.node.json
```

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.

*   `tsconfig.app.json` sets the rules for your `Frontend` or React code.
    
*   `tsconfig.node.json` sets the rules for the `Backend` side or the logic that runs exclusively on the server.
    
*   `tsconfig.json` is the parent file that is read first by the ts-compiler; it holds references to the other two files.
    

## Vite Configuration

### vite.config.ts

We&apos;ve already customized `Git`, `TypeScript`, and `npm`. But what about our engine—Vite?

That&apos;s where the `vite.config.ts` file enters the game.

The file simply exports a `defineConfig` function, which receives a configuration object we can use to fine-tune how `Vite` operates.

Since `Vite` works with most modern frameworks, we need to pass it the `React SWC plugin` to ensure the build process is compatible with `React`.

```tsx
import { defineConfig } from &quot;vite&quot;;
import react from &quot;@vitejs/plugin-react-swc&quot;;

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
});
```

## Application Entry Point

### index.html

`React` is just `Javascript`, and as you may know, `Javascript` can&apos;t exist in the browser without `HTML`. Similarly to how an athlete can&apos;t move his body without its bones.

`index.html` file is the entry point of the application, it defines the main `HTML` layout or template of all the pages that are served.

```html
&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
    &lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; href=&quot;/vite.svg&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
    &lt;title&gt;Vite + TS&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;module&quot; src=&quot;/src/main.ts&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
```

Inside the `&lt;head/&gt;` tag we reference the `/vite.svg` file as a `favicon`. If you look closely, you&apos;ll see that it&apos;s located within the public folder.

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 (`/`) followed by the path relative to the public folder.

## Source Code Directory

The body of the `index.html` contains a script tag that imports the `main.tsx` file located within the `src` directory.

### The src folder

The `src` folder holds all of our application&apos;s `Typescript` code including React components, their corresponding stylesheets and other logic.

### main.tsx - The React Entry Point

```tsx
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(
  &lt;StrictMode&gt;
    &lt;App /&gt;
  &lt;/StrictMode&gt;,
);
```

So where does all the Javascript action happen? -- `main.tsx`. React literally binds itself to the `index.html` here.

Inside the `main.tsx` file, we retrieve the **DOM element** of the `div` with the `id` of `root` using the `document.getElementById(&apos;&apos;)` method.

```html
  &lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;module&quot; src=&quot;/src/main.tsx&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
```

The element is passed to the `createRoot`, a function imported from `react-dom/client`. The function call returns the application&apos;s **root object**.

```tsx
const divDomNode = document.getElementById(&quot;root&quot;)!
const applicationRootObject = createRoot(divDomNode)
 applicationRootObject.render(
  &lt;StrictMode&gt;
    &lt;App /&gt;
  &lt;/StrictMode&gt;,
);
```

After that, we make use of the `render` method of the **root object** to display the `&lt;App/&gt;` component -- Where an example counter component code resides.

&gt; Instead of passing `&lt;App/&gt;` directly to the render method, we wrap it in a `StrictMode` component because it makes catching bugs easier in dev mode.

## Development Server and Testing

Now that we explained briefly, how `React` wires itself and injects the Counter example code defined inside the `&lt;App/&gt;` component inside the `&lt;div/&gt;` with the id of `root`. Let&apos;s start our app to see it happening!

Let&apos;s open our terminal, type `npm or pnpm run dev` in order to start the development server, open your browser, and then head straight to `http://localhost:5173`.

Once you&apos;ve done so, you&apos;ll stumble upon this page.

![Vite Dev Server Running](/assets/courses/vite-server-example-page.png)

Now, in order to confirm that the `main.tsx` file is really injecting the `&lt;App/&gt;` component inside the `div` with the `id` of `root`. Let&apos;s inspect the page.

![Inspect the Root Div](/assets/courses/inspect-root-div.png)

Great! All the Counter&apos;s `HTML` code is here. And it gets even better the `Html` is updating whenever we increment the counter. React is indeed Reacting, and we are reacting to it! Isn&apos;t that crazy?

## Conclusion

There is one missing piece that we didn&apos;t cover yet in this article.

Despite going through the project&apos;s files and folders and explaining how React injects the `&lt;App/&gt;` component into the `&lt;div/&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 `React` application that you can see out there.

Stick around for the next article, where we will address these topics in depth. Until then, Happy coding!</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>beginner</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>PROPS in React explained.</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-props-tutorial-passing-data/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

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.

As you may know, in `React` we represent the user interface as components that are nested within each other, forming a `tree`.

Each **component** is responsible for its own `Markup` and logic.

`React` follows a `unidirectional data flow model`, meaning that information can only be passed from **parent components** to **child components**. In other words, the data only flows in one direction—starting from the top of the tree to the bottom.

## Passing Props Between Components

```tsx
function ChildComponent() {
  return &lt;h1&gt;&lt;/h1&gt;;
}

function ParentComponent() {
  return (
    &lt;div&gt;
      &lt;ChildComponent /&gt;
    &lt;/div&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?

Passing props from one component to another is straightforward. And here&apos;s how it&apos;s done:

1.  Pass the data as attributes, similar to how you would pass `normal attributes` to an `HTML` tag element. -- Here we are passing a `content` attribute with a value of `test.`
    
2.  Now, let&apos;s add a `props` parameter to the child component so that it can access the `content` attribute that we&apos;ve passed before.
    
3.  Finally, make the `ChildComponent` render the `content` value within an h1 tag.
    

```tsx
function ChildComponent(props) {
  return &lt;h1&gt;{props.content}&lt;/h1&gt;;
}

function ParentComponent() {
  return (
    &lt;div&gt;
      &lt;ChildComponent content=&quot;test&quot;/&gt;
    &lt;/div&gt;
  );
```

It&apos;s also possible to access the `content` attribute more conveniently using the destructuring syntax.

```typescript
function ChildComponent({content}) {
  return &lt;h1&gt;{content}&lt;/h1&gt;;
}
```

Unlike normal `HTML` attributes, `props` can include any `JavaScript` value such as: `arrays`, `functions`, or even `JSX` code.

```tsx
function handleClick(){
console.log(&quot;Clicked!&quot;)
}
return(

&lt;ChildComponent content=&quot;test&quot; arr={[1,2,3]} onClick={handleClick}/&gt;
)
```

## Prop Forwarding and Spread Operator

Okay, now let&apos;s say that we have 3 levels of nesting:

1.  A parent component `App` that renders a component named `ChildComponent1` while passing 3 props to it: a title, a description and an image.
    
2.  On the other hand, The `ChildComponent1` renders the content of the `title` inside an `h1` tag and then forwards the `description` and the `image` props to a third component named `ChildComponent2`.
    

```txt
App -{title,img,description}--&gt; ChildComponent1 --{description,image}-&gt; ChildComponent2 
```

This can quickly get cumbersome as the number of forwarded `props` increases. Moreover, the components become less resistant to changes when we want to forward more props.

So instead of forwarding the `props` manually like that

We can only **destructure** the `title`, and use the spread operator syntax to store the remaining `props` in an object called `restProps`.

After that we can pass the rest props to the `ChildComponent2` using this syntax `&lt;ChildComponent2 {...restProps}/&gt;.`

```tsx
function ParentComponent() {
  return (
    &lt;div&gt;
      &lt;ChildComponent1
        title={&quot;This is a message from component 1&quot;}
        description={&quot;description&quot;}
        image={&lt;img src=&quot;...lorem picsum&quot; alt=&quot;image alt&quot; /&gt;}
      /&gt;
    &lt;/div&gt;
  );
}

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

function ChildComponent2({ description, image }) {
  return (
    &lt;div&gt;
      {description}
      {image}
    &lt;/div&gt;
  );
}
```

## Children Props and Layout Components

Some `HTML` 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?

To make a component **wrap other components** or any `JSX` code, we need to use a special `prop` called `children.` And as the name implies, it stores all the `JSX` code that is wrapped by the component.

```tsx
function ChildComponent(){
  return (
  &lt;div&gt;I&apos;m a just a child&lt;/div&gt;
  )

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

function App(){

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

  &lt;/HigherOrderComponent&gt;

)

}
```

## Conclusion

Your `React` component would be nothing more than a static snippet if it weren&apos;t for `React` props, which make it possible to reuse components in different scenarios.

But what if a component receives an`isLoggedIn` boolean value prop and needs to show either a `Login` button or a `Logout` button depending on that value?

That&apos;s where conditional rendering comes in!

In the next article, we will learn how to **display different elements** depending on specific **conditions**, using either `if` statements within the `JavaScript logic` of the component or a `ternary operator` inside the `Markup` itself.

Until then, happy coding 🧑‍💻.</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>intermediate</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>Mastering React Lists &amp; Keys: 0 to Pro in 5 Minutes</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-rendering-lists-map-keys-tutorial/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

In many situations you&apos;ll want to **display multiple** items that **share the same structure and styling** based on a collection of predefined data that might come from **various sources,** including **external APIs**, offline browser storages such as **IndexedDB** or **LocalStorage,** and so on.

Even though the data might come from **various sources,** it always ends up in a **JavaScript array**.

So in this article we will learn **how to render a list of components** or of just raw **JSX** code given an **array of data**.

And then we will understand how **React** can track those **rendered components** via something called **&quot;keys.&quot;** So without any further ado, let&apos;s dive in.

# Code Repetition Problem

Take a look at this code.

```tsx
&lt;ol&gt;
  &lt;li style={{...}} &gt;Item 1&lt;/li&gt;
  &lt;li style={{...}}&gt;Item 2&lt;/li&gt;
  ...
  &lt;li style={{...}} &gt;Item N&lt;/li&gt;
&lt;/ol&gt;
```

Writing code like this is the fastest way to make your project unmaintainable.

Let&apos;s say that you needed to **render a list of items** that have the **same styling and structure** but only **differ in their content**.

## Solution: How to Map an Array of Items into JSX Code.

Instead of writing that whole code and repeating ourselves.

We can just define an **array** of strings that will host all of our data. And then use the **array&apos;s** built-in **map** method to transform each element in the **array** into a different shape.

This is done by passing a **callback function** that defines this transformation.

The callback function will be written as follows: we take the function&apos;s argument, and then we return this **JSX** code that represents the targeted markup of each array element.

In our case, we want to convert each item in the array from a string to JSX code, which consists of the &quot;li&quot; tags wrapping the string.

*   ```tsx
    function App(){
      const  items = [&quot;item 1&quot;,&quot;item2&quot;,&quot;item 3&quot;]
      const JSXItems =  items.map(item=&gt;(&lt;li&gt;{item}&lt;/li&gt;))
      // [&lt;li&gt;Item 1&lt;/li&gt;,&lt;&gt;Item 2&lt;/li&gt;,&lt;&gt;Item 3&lt;/li&gt;]
    
      return (
        /*...code*/
      )
    }
    ```
    
    &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.
    
    ## How to Render an Array of JSX Codes?
    
    Okay, now what? We&apos;ve got an array of JSX elements. But how can we render that?
    
    **React** can only render **two things**: **JSX** code or an array of JSX codes. We can safely render the content of the new array directly in the JSX through the curly braces syntax.
    
    The result will look like this.
    
    ```tsx
    function App(){
      const  items = [&quot;item 1&quot;,&quot;item2&quot;,&quot;item 3&quot;]
      const JSXItems =  items.map(item=&gt;(&lt;li&gt;{item}&lt;/li&gt;)) // array of JSX elements.
      // [&lt;li&gt;Item 1&lt;/li&gt;,&lt;&gt;Item 2&lt;/li&gt;,&lt;&gt;Item 3&lt;/li&gt;]
    
      return (
        &lt;ol&gt;
        {JSXItems}
        &lt;/ol&gt;
      )
    }
    ```
    
    ## A Richer Example: Rendering an Array of Todos!
    
    Now that we&apos;ve got the basics, let&apos;s deepen our understanding by walking through a more involved example.
    
    Picture this: we have an array of todo objects, each one possessing the following attributes:
    
    *   An **ID** that uniquely identifies each object.
        
    *   A **todo has a &quot;name,&quot; a &quot;description,&quot; and a &quot;completed&quot; boolean** variable representing whether a given todo is completed or not.
        
    
    ```tsx
    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,
      },
    ];
    ```
    
    Similar to our previous example, we can use the **&quot;map()&quot;** 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.
    
    ```tsx
    const todosJSX =  todos.map(item=&gt;(
          &lt;div&gt;
            &lt;h2&gt;{item.name}&lt;/h2&gt;
            &lt;p&gt;{item.description}&lt;/p&gt;
            &lt;p&gt;{item.completed ? &quot;✅&quot;  : &quot;❌&quot;}&lt;/p&gt;
          &lt;/div&gt;
    ))
    ```
    
    Now let&apos;s just render the array in the **App** component&apos;s **JSX** code.
    
    ```tsx
    function App(){
      // ...code for todos
    const todosJSX =  todos.map(item=&gt;(
          &lt;div&gt;
            &lt;h2&gt;{item.name}&lt;/h2&gt;
            &lt;p&gt;{item.description}&lt;/p&gt;
            &lt;p&gt;{item.completed ? &quot;✅&quot;  : &quot;❌&quot;}&lt;/p&gt;
          &lt;/div&gt;))
      return (
        &lt;div&gt;
          {todosJSX}
        &lt;/div&gt;
    
      )
    }
    ```
    
    That&apos;s how easy it is to render an array of objects. It&apos;s that simple; just map it to **JSX** elements, and you&apos;re good to go 😄.
    
    Now as the JSX returned by the **map&apos;s callback function** is getting quite long and messy, let&apos;s substitute it or move it into its own react component
    
    First, create a **&quot;TodoItem&quot;** component, receiving the necessary props and returning the previous JSX code.
    
    ```tsx
    function TodoItem({name,description,completed}){
    
      return (
          &lt;div&gt;
            &lt;h2&gt;{name}&lt;/h2&gt;
            &lt;p&gt;{description}&lt;/p&gt;
            &lt;p&gt;{completed ? &quot;✅&quot;  : &quot;❌&quot;}&lt;/p&gt;
          &lt;/div&gt;
      )
    }
    ```
    
    Then let&apos;s call it in the map&apos;s **callback function** and pass the props by spreading the todo object instead of passing each attribute separately.
    
    ```tsx
    function App(){
      // ...code for todos
    const todosJSX =  todos.map(todo=&gt;(&lt;TodoItem {...todo}/&gt;))
      return (
        &lt;div&gt;
          {todosJSX}
        &lt;/div&gt;
    
      )
    }
    ```
    
    &gt; As you can see bellow spreading the todo object makes the component more readable and maintainable.
    
    ```tsx
    const todosJSX =  todos.map(todo=&gt;(&lt;TodoItem title={todo.title} description={todo.description} completed={todo.completed} /&gt;)) 
    
    // VS
    const todosJSX =  todos.map(todo=&gt;(&lt;TodoItem {...todo}/&gt;)) // ✅ Better and more concise
    ```
    
    Now our code is much cleaner and easier to read.
    
    # How can React track many rendered components?
    
    So what are keys? Why are they so important to React?
    
    When calling the same component twice or rendering an array of components, it&apos;s important to pass a unique key to each component.
    
    In fact, if you try to render a list of items without passing the **key** prop into each one, you will get an error. The following warning gets displayed in your browser console.
    
    &gt; ⚠️ **React Warning:** Each child in a list should have a unique &quot;key&quot; prop.
    
    When using the **map** method to render an **array** of items, we should always pass a **string** or a **number** **key** prop that **uniquely identifies each item among other items in the array**.
    
    The **keys** help **React** 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 **JSX** items.
    
    That may seem not important when the **array** is not changing. But if it **gets mutated or changed** by either **sorting it, deleting or inserting an item, etc.**
    
    **React** can have a hard time tracking items because, **by default, it&apos;s using the item&apos;s array index** as a **key,** which is obviously not stable when deleting or inserting items or sorting the array.
    
    The **keys should also be stable**, or in other terms, **they should not change every time the component gets rendered** in order to optimize updating the DOM tree and therefore your application&apos;s performance.
    
    The easiest way to make sure that the **ID** is stable is to **include it in the data itself, as we did previously when defining the todo list item object**.
    
    Right inside the **&quot;map&apos;s&quot;** callback function, let&apos;s assign the `todo.id` attribute to the component&apos;s key prop.
    
    ```tsx
    const todosJSX =  todos.map(todo=&gt;(&lt;TodoItem key={todo.id} {...todo}/&gt;)) 
    ```
    
    The same thing applies if **JSX** code were returned; just pass the key prop to the upper wrapping element as shown below.
    
    ```tsx
    const todosJSX =  todos.map(item=&gt;(
          &lt;div key={todo.id}&gt;
            &lt;h2&gt;{item.name}&lt;/h2&gt;
            &lt;p&gt;{item.description}&lt;/p&gt;
            &lt;p&gt;{item.completed ? ✅  : ❌}&lt;/p&gt;
          &lt;/div&gt;))
    ```
    
    An interesting case that we should absolutely highlight here is when returning multiple **JSX** 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 [JSX](./jsx-tutorial-react-javascript-guide.md) article.
    
    If you have tried to set the prop **key** to the shorthand version of the **React** fragment syntax, your editor will highlight it as a syntax error. Because that&apos;s not allowed.
    
    ```tsx
    function Test({id}){
    
      return (
        &lt;key = {id}&gt; {/* Not allowed ❌*/}
        &lt;h1&gt;Title&lt;/h1&gt;
        &lt;div&gt;Random description text&lt;/div&gt;
        &lt;/&gt;
      )
    }
    ```
    
    Instead, you&apos;re required to use the longer version, which consists of wrapping your returned children with the **&quot;React.Fragment&quot;** tag.
    
    Then you can pass the key prop as you usually do with any JSX tag or component.
    
    ```tsx
    import React from &quot;react&quot;
    function Test({id}){
    
      return (
        &lt;React.Fragment key = {id}&gt; {/*  allowed ✅*/}
        &lt;h1&gt;Title&lt;/h1&gt;
        &lt;div&gt;Random description text&lt;/div&gt;
        &lt;/React.Fragment&gt;
      )
    }
    ```
    
    # Conclusion
    
    So that&apos;s how you simply render lists in **React**: just map your array to JSX code, create new subcomponents as needed, and most importantly, **never forget your keys**.
    
    We’ve got our keys and our components, and our list is rendering perfectly. **But there is one critical detail we’ve skipped.**
    
    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.
    
    In the next article we&apos;re going to **unveil how we can seamlessly respond to those events**.
    
    Until then, happy coding!</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>intermediate</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>Why your React State isn&apos;t updating (The Snapshot Trap)</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-state-snapshots-explained/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>```javascript

function App(){
  const [counter,seCounter] =useState(1)
return (
  &lt;div&gt;
    &lt;p&gt;{counter}&lt;/p&gt;
    &lt;button onClick={()=&gt;{

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

    }}&gt;&lt;/button&gt;
  &lt;/div&gt;
)
}
```

**You might be shocked to know that this code will NOT print 2. 😮**

Think about it: we increment the counter, then defer the console log by 5 seconds using the `setTimeout` API. By the time that log finally executes, the state has already been updated to 2 on your screen.

**But the console shows a different reality: a &quot;1&quot; gets printed every single time. 🤯**

It feels like a glitch, but it’s actually React working exactly as intended. In this article, we’re going behind the scenes to clarify exactly what’s happening by explaining the concept of a **state snapshot.**

So, without any further ado, let’s get started.

## useState Returns a Snapshot—A copy of the original state

As you might know, state doesn&apos;t live inside the function component, but it&apos;s stored within the **React** package itself!.

And **provided as a snapshot** or, in other terms, as **a copy of the original state** via the **useState** hook.

In fact, **useState** is named a hook because it&apos;s hooking into the external state stored in **React** itself.

## Why is the code printing &quot;1&quot; instead of &quot;2&quot;?

Component re-renders can be triggered via state updates. Therefore, when a given component re-renders\*\*,\*\* a new snapshot mirroring the latest updated state value is given to it, and then based on that value, the whole **JSX,** including the **attached event handlers,** gets re-created again.

By the time the second render happens, the whole **JSX,** including its corresponding **attached event handlers,** will be re-created again with the **new counter state value, which will be equal to 2**. But the previous event handler that has fired will only have access to the previous state snapshot with its corresponding JSX code. Therefore, the code prints 1.

So, **every render is associated with** the following:

*   **A state snapshot**.
    
*   And JSX **code including event handlers.**
    

Similarly, if you try to re-click on the **button** again, **the counter state will be incremented to 3**.

Then the component will **re-render displaying 3 on the UI**. After 5 seconds have elapsed, 2 will be printed because, as we said previously, the event handler was attached to the previous render; hence, the **callback function** is referencing the **old state snapshot**.

In other words, we can briefly say that **the state that is returned by the useState hook is constant during every render.**

Even if the event handler that is attached to one of the returned **JSX** elements were executing asynchronously in the future when many potential renders may have already occurred.

Every render is allocated its own constant **state** snapshot that never changes before the next render.

All the derived **JSX** code, including **event handlers,** is tied to that specific render.

In more specific words, **renderers are totally isolated**.

&gt; Render 1 can never access state snapshots in render 2.

## Conclusion

To sum up, you can think of a **re-render** as a component starting a brand **new life** with a brand **new state snapshot**, **JSX code,** and **event handlers**.

Now take a look at this code.

```tsx
// counter = 1
setCounter(counter +1)
setCounter(counter +1)
// counter = ?? 
```

Imagine if we try to update the **counter** state using &quot;**setCounter,&quot;** the setter function, two times sequentially. What would be the value of the **counter** state after the second render?

Well, that&apos;s what we are going to discover in the next article, where we introduce **React State Batching**.

Until then, happy coding!</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>advanced</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>100 Renders, 1 UI Update: The Virtual DOM Secret to Why React is Actually Fast.</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-three-phases-trigger-render-commit/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

Did you know that a **React** component can re-render while the corresponding displayed **UI** segment has not been changed?

I know **when we say rendering, we instinctively think that something has to be printed on the screen**. But that&apos;s not necessarily the case for **React** 🤯.

In fact, React has to go through three whole phases before even touching the UI.

In this article, we’re going to explore:

Why is updating the UI—or the DOM directly—considered so expensive for the browser? How React solves that bottleneck by **planning** first in the **trigger** and **render** phases, then updating the UI in the **commit phase**.

So without any further ado, let&apos;s jump straight to answering the first question: Why are browser UI updates considered expensive?

## Why are browser UI updates considered expensive?

Updating your application&apos;s **UI**, which is displayed on your browser screen, involves **performing a series of operations** on the **DOM,** or the **Document Object Model,** which is **an object representation of the parsed HTML code that is required to display the UI**.

If **React** were updating the **DOM** **every time a component had re-rendered**, **the number of DOM operations performed could become huge**. Therefore, your application&apos;s performance would be negatively affected.

Moreover, we shall say that **updating the DOM is considered a costly operation in general**. Especially **if performed too often** because of the following reasons:

### Browser Reflows

*   First, **DOM** operations **trigger browser reflows,** during which it **has to recalculate the layout of the entire page, or a large part of it**. For example, when an element gets removed from the **DOM**, **the positions of the other elements need to be recalculated again**. The **more elements on the page, the more expensive these recalculations become**.

### Browser Repainting

*   Secondly, after **reflow**, the browser may need to **repaint the affected parts** of the screen. **Repainting** involves **redrawing elements** (borders, shadows, colors, shapes, and so on). Despite being lighter than **reflow,** it&apos;s **still not counted as a trivial operation**.

### DOM updates are synchronous.

*   Finally, in addition to **reflow** and **repaint**, **DOM** updates are **synchronous,** which means that they can **block UI interactions** and ruin the entire user experience **(UX).**

Fortunately, **React does not touch the DOM when a component renders**. But if rendering isn&apos;t painting, then what is it?

Well put simply, **rendering** is nothing more than the process of **calling your function component by React**, which is way faster than **DOM** updates.

## The Three Phases

In order to avoid updating the DOM on every render, **React** is **splitting the work into 3 phases**: **trigger**, **render,** and **commit**. The **DOM** updates are **deferred** to the last phase (**the commit phase**).

### 1\. Trigger Phase

A reaction can&apos;t happen without something that triggers it. So before rendering the component, something should tell it, &quot;Hey, some state has changed here; please re-render component A.&quot;

A render can be triggered by **two different reasons**:

*   Initial Render.
    
*   Re-rendering.
    

#### **Initial Render**:

The initial rendering happens **when the whole component tree gets initially rendered**.

As you may know, your app gets initially rendered via the **React** root element, which is created by the **createRoot** function that is imported from &quot;**react-dom/client.&quot;**

```tsx
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(
  &lt;StrictMode&gt;
    &lt;App /&gt;
  &lt;/StrictMode&gt;,
)
```

The **createRoot** function receives the wrapper **DOM** node, where the final rendered **HTML** that corresponds to your component&apos;s tree needs to be injected (root **div**). And then **renders your component tree given the parent App component**.

So the first render happens when the **React** root render method gets initially called.

#### **State Updates**:

Once **your component tree has been initially rendered, further renders** can be triggered by **calling the setter function returned by the &quot;useState&quot; hook**.

**Whenever the setter function is called**, **React** queues or schedules a future render. Even if you&apos;ve called the **setter function** **multiple times**, the **new state** won&apos;t be reflected until the **next render**.

Put differently, using the **setter function** means just asking **React** for a future render while mentioning the state changes.

**React** will take that into consideration and schedule the next render with the **new state value**. **Consequently, it will update the parts of the JSX code that are derived from the new state** during the next render.

### 2\. Render Phase

Now let&apos;s move into the second phase that comes after **triggering a render**, which is obviously **rendering**.

To put it in simple words, **rendering is just when React decides to call your function component**.

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.

When a specific component&apos;s state changes, all of its direct or indirect children will re-render recursively. In other words, 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.

Each component in the tree will return the JSX code that corresponds to the UI segment that it is responsible for.

As we saw in the JSX article, despite looking like **HTML code,** it&apos;s just a **JavaScript** language extension, meaning that it&apos;s getting converted into a bunch of objects representing the real **HTML** DOM nodes.

During the initial render of the component&apos;s tree, React builds a **virtual representation of the real DOM** as raw **JavaScript** objects.

In addition to that, 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 **JSX** returned by some components may differ compared with the initial re-render.

**React will keep track of all the changes that are caused by the re-renders** while **calculating a minimal number of DOM operations that are needed to move from the previous state (before rendering) to the newest state (after rendering)**.

### 3\. Commit Phase

After the process of re-rendering, during which **React creates a bunch of objects representing the DOM elements** and **calculates a lot of information regarding the minimal required DOM operations to get from the oldest state to the newest**.

**React** will finally start modifying the **DOM** during what is called the **commit phase**.

Obviously, the commit or the DOM update always happens at the end. Either when the component is **initially rendered** on the app start or when **it gets re-rendered because of a triggered state update**.

During **the initial rendering** and just after rendering all the components in the tree, **React** reads the **virtual DOM**, or the lightweight JavaScript object representation that was created during the rendering phase. And then uses the **DOM** API to insert all the nodes inside the wrapping **div** with the root **ID**.

**When it&apos;s not an initial rendering but one that happened after a state update.** **React** will use both the **virtual DOM** and the **diffs&apos;** information collected during the **rendering phase** and then apply a minimal number of **DOM** operations in order to make it match the latest rendering output.

React is smart enough to only change the **DOM** nodes that have been modified during the previous phase.

## Conclusion

By **delaying DOM operations to the commit phase** and **calculating the optimal number of DOM operations after re-rendering**.

**React** manages to achieve great performance while simplifying the process of **UI** development by taking care of the **complex stuff like DOM manipulation** and providing you, the user, with a **simple and descriptive language** that allows you to model the **UI** as a function of its state using **React** components.

```
UI = fn(State)
```

In this article, we covered the three phases that React abides by before rendering your UI. But there are a few things that we haven&apos;t gotten the chance to totally unveil yet.

One of those things is regarding the relationship between rendering and the state value. And the fact that the state value that is returned by useState is actually just a snapshot of the current state. In fact, every time the component renders, a new snapshot gets served to the component.

We’ll dive deeper into the mechanics of the state snapshot in the **next article.**

Until then, happy coding.</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>advanced</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>Learn useState In 10 Minutes - React Hooks Explained</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/react-usestate-hook-state-management/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/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, 05 Mar 2025 00:00:00 GMT</pubDate><content:encoded>## Introduction

Modern web applications are **highly interactive**; users can **click on buttons, fill out forms, toggle navbars, play a video, and so on**.

**Interactivity** makes the **UI**, therefore the **React** components change as the time wheel rolls by.

When you type on an **input** field, the wrapper component should keep track of **the last typed value**.

If you **toggle** a **navbar**, it should **always stay toggled** and never get reset back to its previous state as long as we&apos;ve never clicked on the toggle **button** again.

In other words, sometimes a **React** component needs some kind of **local and personal memory** to remember what&apos;s needed to **accomplish its mission**.

This specific type of memory is called a component&apos;s **local state**. It is the heartbeat of any interactive application, and it is the focus of today’s article.

To master state, we need to understand not just _how_ to use it but _why_ React handles it so specifically. We will dive into:

*   **Why a locally declared variable can&apos;t serve as state for the component.**
    
*   **The useState hook:** We will introduce the React way of dealing with states, explaining the intuition behind it and how to use it **properly**.
    

## Why isn&apos;t a locally declared variable enough?

Let&apos;s say that we want to create a basic **counter** component that supports **incrementation, decrementation, and reset operations**.

Or in other words, a **React** component that **renders a count variable** while **providing buttons for incrementing, decrementing, and resetting that counter.**

We will declare the **count** variable locally using the **&quot;let&quot;** keyword and then render it in the JSX via the curly braces syntax.

```tsx
function App(){
  let count;

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

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

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

      &lt;button onClick={(e)=&gt;{
        count = 0;
        console.log(count)
      }}&gt;Reset&lt;/button&gt;
    &lt;/div&gt;
    &lt;/div&gt;
  )
}
```

Each **button** is attached to an **event handler** that changes the **&quot;count&quot;** variable depending on the operation.

**Adding one on the incrementation,** **subtracting one on the decrementation,** and **resetting the variable to zero** when the reset button is clicked.

Now, let&apos;s **try to increment** the **&quot;count&quot;** while checking the console logs in the inspect window in parallel.

![Counter Example with a local variable](/assets/courses/counter-example-no-use-state.png)

As you can tell, the &quot;**count&quot;** variable is indeed getting incremented with every click, but the displayed &quot;count&quot; value in the UI is stuck at 0.

Said differently, **the component is not re-rendering the JSX when we increment the variable**.

&gt; Notice that the UI updated message got printed two times even tough the component have only rendered one time. Well, By default **React** uses **Strict mode** in development environment for debugging reasons, that&apos;s why the message got printed twice. In production environments, **Strict mode** gets disabled, thus only 1 render will occur.

Come on, how is it even possible to call this framework **React** if it&apos;s not reacting to the **&quot;count&quot;** variable changes by **re-rendering the component and updating the UI**?

![React waiting for a state update when you mutate a local variable](/assets/courses/react-waiting-for-updates-local-variable.jpg)

Well, the reason behind that is that changes to the locally declared **&quot;count&quot;** **variable** can&apos;t trigger a re-render. Or in other terms , **no one is telling React that the &quot;count&quot; variable has changed**.

Let&apos;s suppose that the &quot;count&quot; variable is indeed triggering a re-render. Will that be enough?

Think about it; even if a re-render gets triggered, the variable will get re-declared again and reinitialized to zero.

So to summarize all that has been said, we need two built-in mechanisms to make the counter-example work:

1.  Something that tells **React** that a given **state variable** has changed, therefore triggering a component&apos;s re-render and then updating the **UI**.
    
2.  And a way to persist data or **state** between the component&apos;s re-renders so that our **&quot;count&quot;** variable value will never get reset or lost between re-renders again.
    

Fortunately, **React** has to **react** to this by providing a built-in utility function called **&quot;useState.&quot;**

![React Provides useState](/assets/courses/react-provide-use-state.jpg)

## Introducing &quot;useState&quot;: The React way of Dealing with State

```tsx
import {useState} from &quot;react&quot;
function App(){
  const stateTuple = useState()
  const [state, setState] = stateTuple

}
```

**useState** returns what is known as a **tuple,** which is just a fixed-size array.

In our case it has a fixed length of two **items**, the first being the **state** variable that persists between re-renders and the second one being a setter function, &quot;**setState**,&quot; that can be used to update the state while triggering a re-render.

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.

```tsx
import {useState} from &quot;react&quot;
function App(){
  const [state, setState] = useState()
}
```

The items are usually named **variableName** followed by **setVariableName,** but you&apos;re free to name them as you prefer.

Moreover, **useState** 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 **&quot;count&quot;** and a corresponding setter function named **&quot;setState&quot;** while ensuring that the &quot;**count&quot;** variable defaults to zero.

```javascript
const [count, setCount] = useState(0)
```

Let&apos;s refactor the event handlers to set the **&quot;count&quot;** using the &quot;**setCount&quot;** **setter function** instead of **mutating the variable directly**.

```tsx
function App(){
  import {useState} from &apos;react&apos;;
  const [count, setCount] = useState(0)
  console.count(&quot;UI: Updated&quot;)

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

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

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

}
```

Now, let&apos;s try to increment, decrement, and reset the &quot;**count.&quot;**

![useState counter example](/assets/courses/react-use-state-counter-example.png)

Great! In contrast with the previous example, now the **UI** reacts to the **count** variable **updates** and **changes whenever the count variable gets modified**.

Or, said differently, **the component re-renders when the &quot;count&quot; variable gets modified with the setter function**.

Even though the code inside the component re-runs entirely when re-rendering, the state still gets persisted between all the re-renders.

## Hooks Rules

In **React**, any function starting with **&quot;use&quot;** is called a **hook**.

Therefore, useState is one of **React**&apos;s built-in **hooks**.

It&apos;s true that **hooks** are ordinary **JavaScript** functions, but you can&apos;t use them everywhere in your **JavaScript** application.

Any happy marriage implies adhering to a bunch of predefined constraints, and so too does your relationship with **React** **hooks**.

### First Rule

The first rule is simple yet overlooked by many developers.

You just need to make sure that you&apos;re declaring your React hooks at the top level of the component

In other words, just after the opening curly braces &quot;**{}&quot;** of the component&apos;s function declaration.

That being said, don&apos;t even think about using hooks inside **loops**, **conditions**, **try/catch/finally blocks**, or **JSX markup.**

```tsx
import { useState } from &quot;react&quot;
function App(){
  // Loops ❌

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

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

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

    const [counter,setCounter] = useState(0)
  }while(true)
  
}
```

```tsx
import { useState } from &quot;react&quot;

function App(){
  if(true){ // Conditions ❌
    const [counter,setCounter] = useState(0)
  }
}
```

```tsx
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 ❌
  }
}
```

Instead always use them at **the top level** of your **function component** **before any early return statement**.

```tsx
import {useState} from &quot;react&quot;
function App(){
      const [counter,setCounter] = useState(0) // ✅

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

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

Usually, **React** will let you know when you&apos;ve broken one of these rules with a detailed error message.

### Second Rule

The second rule is non-negotiable: Hooks belong **exclusively** inside React function components.

You might wonder, &quot;Can _I just sneak a_ **_hook_** _into a regular_ **_JavaScript_** _function or a class?&quot;_ Well, it depends on whether or not you want your app to **blow up in your face**

Hooks aren&apos;t designed to work with ordinary functions; their goal is to hook into React internals to give you total control over the components.

```tsx
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)=&gt;{
  const [counter,setCounter] = useState(0) // ❌
  }
  
}
```

## How State Updates Work

Now that we&apos;ve discussed the rules for having a happy relationship with React hooks, let&apos;s get back to our previous counter-example and **break down** what&apos;s happening under the hood.

When we click on the increment **button,** the **click event** gets fired; therefore, **the event handler will start running**.

Inside the event handler&apos;s code, the &quot;**setCount&quot;** function gets called with the current **count** state value, which is equal to zero plus one, as an argument.

```tsx
setCount(count + 1) // count=0
```

Calling the latter triggers a second re-render or tells **React,** &quot;Hey, some state got updated here; please re-render the component and then update the **UI**.&quot;

Even though the &quot;**setCount&quot;** function executes on the current render, the &quot;**count&quot;** state value will remain equal to 0 until the next render.

```tsx
function App(){
  // First Render

  //...code

  // count = 0

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

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

}
```

In other words, React queues all the updates of the current render in memory until the next render happens, where the **UI** will get constructed depending on the new state value.

On the second render, the &quot;**count&quot;** state will be incremented; therefore, it will be equal to 1, the component will execute from top to bottom, return the **JSX** with the updated **count** state value, and finally **React** will update the **real** **DOM** in the user&apos;s browser.

```tsx
function App(){
  // Second Render

  //...code

  // count = 1

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

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

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

}
```

## Multiple Components and State

Let me ask you a question now. What would you expect if we had called the **Counter** component two times in the **App** component? What would happen if we incremented one of them?

```tsx
function Counter(){
  /*Previous counter code*/
}

function App(){
  return(
    &lt;div&gt;
      &lt;Counter/&gt;  {/* count = 1*/}
      &lt;Counter/&gt;  {/* count = 0 */}
    &lt;/div&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.

## Multiple State Variables

Another question that may traverse your mind is, can we use more than one state in a **React** component?

The answer is absolutely yes, we can do that.

Let&apos;s take this &quot;**Greeting&quot;** component as an example.

```tsx
function UserGreeting() {
  const [name, setName] = useState(&apos;Guest&apos;);
  const [showGreeting, setShowGreeting] = useState(true);
  
  return (
    &lt;div&gt;
      {showGreeting &amp;&amp; &lt;p&gt;Hello, {name}!&lt;/p&gt;}
      &lt;button onClick={() =&gt; setName(name === &apos;Guest&apos; ? &apos;User&apos; : &apos;Guest&apos;)}&gt;
        Toggle Name
      &lt;/button&gt;
      &lt;button onClick={() =&gt; setShowGreeting(!showGreeting)}&gt;
        {showGreeting ? &apos;Hide&apos; : &apos;Show&apos;} Greeting
      &lt;/button&gt;
    &lt;/div&gt;
  );
}
```

Here we are declaring two pieces of state: one holding the **name,** which can be either &quot;**Guest&quot;** or &quot;**User,&quot;** and the other one is a **boolean** named **&quot;isGuest&quot;** controlling whether to show the greeting message or not.

```tsx
  const [name, setName] = useState(&apos;Guest&apos;);
  const [showGreeting, setShowGreeting] = useState(true);
```

The component **conditionally renders a greeting message** at the top along with **two action buttons at the bottom**.

*   The greeting message is only shown when the &quot;**showGreeting&quot;** state is set to &quot;**true.&quot;** The message consists of a &quot;**p&quot;** tag wrapping a **&quot;Hello&quot;** string and the current **name** state value.
    

```tsx
      {showGreeting &amp;&amp; &lt;p&gt;Hello, {name}!&lt;/p&gt;}
```

*   The first action button is responsible for toggling the **name** state between &quot;**Guest&quot;** and &quot;**User.&quot;**
    

```tsx
      &lt;button onClick={() =&gt; setName(name === &apos;Guest&apos; ? &apos;User&apos; : &apos;Guest&apos;)}&gt;
        Toggle Name
      &lt;/button&gt;
```

*   The second one toggles the &quot;**showGreeting&quot;** state between **true** and **false**.
    

```tsx
      &lt;button onClick={() =&gt; setShowGreeting(!showGreeting)}&gt;
        {showGreeting ? &apos;Hide&apos; : &apos;Show&apos;} Greeting
      &lt;/button&gt;
```

With all that being said, we can conclude that using two **states** or more is a completely viable and easily achievable option in **React** as long as we respect the laws of hooks. Because React is internally relying on the order of useState calls to distinguish between the different states.

## Conclusion

Without state, our application becomes just a boring website with no interactivity. In other words, the building blocks that constitute our UI will never change after the first render without the notion of state.

It&apos;s true that we&apos;ve gone through the **intricacies** of &quot;**useState&quot;**—starting from the **intuition** behind it and the law of hooks to how and why a component can have multiple private states and, finally, **how it all works**.

But we&apos;ve just scratched the surface of **useState**. There are many other **intricacies** that we **haven&apos;t** mentioned yet—the **kind of things** that can save you hours of debugging.

In the next article, we will be diving deeper into how React goes from rendering to displaying the UI on the user&apos;s browser screen.

Thank you for your attentive reading and happy coding!</content:encoded><category>frameworks</category><category>javascript</category><category>frontend</category><category>intermediate</category><category>concepts</category><author>sid-ali-assoul</author></item><item><title>What is React?</title><link>https://notjustcoders.com/courses/react-fundamentals-course/chapters/what-is-react-javascript-library/</link><guid isPermaLink="true">https://notjustcoders.com/courses/react-fundamentals-course/chapters/what-is-react-javascript-library/</guid><description>An introduction to React, its core concepts, and why it has become one of the most popular JavaScript libraries for building user interfaces.</description><pubDate>Wed, 05 Mar 2025 00:00:00 GMT</pubDate><category>frameworks</category><category>javascript</category><category>frontend</category><category>beginner</category><category>concepts</category><author>sid-ali-assoul</author></item></channel></rss>