Everything about React JS.
Tags: javascript, webdev, react, beginners
Published: 2022-01-30 18:39:58

React is free, open-source & component-based front end library which is responsible for the frontend of the application. It is developed and maintained by Facebook.

React was the most popular JavaScript library in 2021.

React is flexible, easy to learn & has a great community support.

If you want to learn the framework that will give you the best odds of landing a job in 2022, your best bet is still React.

## Prerequisites

- [Node.js](https://nodejs.org) installed on your computer
- Basics of HTML, CSS & JavaScript
- Basic understanding of the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction).

## In this blog

- Essential React Concepts (creating react app, Components, JSX, Props, State, Hooks)
- Counter Application
- How to fetch data from an API in React

## Setup & Installation

Open your favorite text editor & let's get started.
(I will be using Visual Studio Code)

Open your command prompt (windows) or terminal (Mac).

Make sure you have installed Node JS (npx comes with Node JS)

![Node JS installed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0jk9v5lgerl0tx740us.PNG)

In your terminal:

```
npx create-react-app react-basic-concepts
```

This will create a new react app with name _react-basic-concepts_

![create-react-app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4p9zv0zoaa1zplz34jb.PNG)

You can see React app is installed in my ADMIN folder.

Now, let's run our application. In your terminal

```
cd react-basic-conecpts
npm start
```

This will run our app on localhost:3000

![localhost:3000](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehv1a591sddeeswjt9ms.PNG)

Now open _react-basic-concepts_ folder in your text editor

![app.js file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0acvpzkg388a542feqk3.PNG)

Let's understand the project structure, you'll see a _**/public**_ and **_/src_** directory with the regular **_node_modules_** (conatins all dependencies), **_.gitignore_**, **_README.md_**, and **_package.json_**.

In **_/public_**, our important file is **_index.html_**
The **_/src_** directory will contain all our React code.

Let's do some cleanup & remove unnecessary files.

In _**src**_ directory keep these files & delete rest of them.

![Folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umzzwk4no79m6ud5oar3.PNG)

Your **_index.js_** file should look like this

![index.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5w65aci6x7mze4b6uzsm.PNG)

Delete everything from **_App.js_**
Open **_App.js_** file & let's create our first component.

```
import React from "react";  // importing React

const App = () => {         // creating App component
  return (
    <div>                   // JSX (we'll look into this later)
      <h1>Hello, world!</h1>
    </div>
  );
};

export default App;         // exporting App
```

Save your file & go to your browser, you'll see **_Hello, world!_**

![Hello, world!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r72yp2nvd4k9wgm971nk.PNG)

Congratulations on creating your first React Component!

## Basic Concepts

### Components

React components let you break up the UI into separate pieces that can then be reused in your entire project.

![Components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20xe5obd6cds5b8p3ek0.jpeg)

Components are independent & reusable pieces of code.

There are two ways of creating a component in React

- Function Components

A React functional components is nothing but a regular JavaScript function that returns JSX.

```
import React from "react";

const App = () => {   component
  return (
    <div>
      <h1>Hello, world!</h1>
    </div>
  );
};

export default App;
```

- Class Components

A class component is JavaScript class with render method.

```
export default class HelloMessage extends React.Component {
  render() {
    return (
      <div>
        Hello, world!
      </div>
    );
  }
}
```

Functional components are short, simple, easy to read & maintain.

However, the rendering time and performance in either components do not make a lot of differences.

> Note: Always start component names with a capital letter.

### JSX: JavaScript + XML

Instead of putting JavaScript into HTML,
JSX allows us to put HTML into JavaScript.

Take a look at the below code:

```
const jsx = <h1>This is JSX</h1>
```

JSX stands for JavaScript XML.
It is simply a syntax extension of React.
It allows us to directly write HTML in React.

To add JavaScript inside JSX, we need to write it in curly brackets:

```
const App = () => {
 const name = "Pratham";
 return (
  <div className="App">
   <p>Hello, {name}</p>
  </div>
 );
};
```

> Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
> For example, class becomes className in JSX, and tabindex becomes tabIndex.

### Props

Props is short for properties and they are used to pass data between React components.

To use props, you have to pass props as argument in our JS function.
Take a look at example below:

/src/App.js

```
import React from "react";
import Names from "./Components/Names";

const App = () => {
  return (
    <div>
      <Names name="Pratham" />
      <Names name="Pratik" />
      <Names name="Saif" />
    </div>
  );
};

export default App;
```

Create new folder in /src & name it components, then create Name.js file in /src/components

/src/Components/Names.js

```
import React from "react";

const Names = (props) => {
  return (
    <div>
      <h1>Hello, {props.name}</h1>
    </div>
  );
};

export default Names;
```

Open localhost:3000 you should see:

![Hello, {name}](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9wz03fz3f4h7el9u32e.PNG)

### Hooks

Hooks allow us to add state to add state to functional components and to share logic across components.

(Note: Hooks can only be used inside function components.)

React have few built-in hooks like useEffect, useState, etc. You can also create your own custom hooks in React.

Let's take a look at _useState_ hook by creating a counter application

### Basic Counter application

Create new component in /src/Components

```
import React, { useState } from 'react';

function Counter() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;
```

_count_ stores the initial value & _setCount_ is used to update that value.

Here, the initial value of the _count_ is 0, then _setCount_ function is used to update the value of _count_.

Render Counter in App.js & open localhost:3000 in your browser

```
import React from "react";
import Counter from "./Components/Counter";

const App = () => {
  return (
    <div>
      <Counter />
    </div>
  );
};

export default App;
```

You can learn more about React hooks [here](https://www.freecodecamp.org/news/introduction-to-react-hooks/).

## Working with API in React

To fetch data from an API in react we will be using _useEffect_ hook.

To understand the useEffect hook you first need to understand lifecycle of the component. The lifecycle of the component contains three main parts i.e. mounting, updating and unmounting.

mounting: when the page loads
updating: when the state updates
unmounting: when user leaves the page

In this case, we will fetch our data:

```
useEffect(() => {
 // data fetching here
}, []);
```

The above code will fetch data when component mouts, that means, on the first render when the page loads.

Let's fetch data from books API.

```
// + add the useEffect import
import { useState, useEffect } from "react";

function App() {
  const [books, setBooks] = useState(null);

  // + adding the use
  useEffect(() => {
    getData();

    // we will use async/await to fetch this data
    async function getData() {
      const response = await fetch(
        "https://www.anapioficeandfire.com/api/books"
      );
      const data = await response.json();

      // store the data into our books variable
      setBooks(data);
    }
  }, []);

  return (
    <div>
      <h1>Game of Thrones Books</h1>

      {/* display books from the API */}
      {books && (
        <div className="books">
          {/* loop over the books */}
          {books.map((book, index) => (
            <div key={index}>
              <h2>{book.name}</h2>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default App;
```

Now open localhost:3000 & see the magic

## Some resources to learn React

[Official documentation](https:reactjs.org)

[Practical React series by Ben awad](https://youtube.com/playlist?list=PLN3n1USn4xlntqksY83W3997mmQPrUmqM)

[30 days of React](https://github.com/Asabeneh/30-Days-Of-React)

That was hell lot of a knowledge.
I'm proud of you if you've managed to make it till here.

**IF YOU ENJOYED THIS, THEN YOU CAN BUY ME MY FIRST COFFEE EVER, THANK YOU**

<a href="https://www.buymeacoffee.com/pratham10" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

**Happy coding!**