JavaScript Concepts to Master Before Learning React

React, being the most liked library for frontend development, attracts many people who wish to learn it. Essentially, ReactJS is a form of JavaScript. However, it is not necessary to know all of JavaScript before starting with ReactJS. If you get the basic ideas in JavaScript, it makes learning React simpler and helps you work on projects faster.

JavaScript concepts to master before learning React; Source: YouTube

Let's outline essential concepts you should know about JavaScript before moving to ReactJS.

1. JavaScript Basics

React is a framework for JavaScript and you will use JavaScript a lot when writing React code. So, it's very clear that knowing the basic ideas of JavaScript is important.

When I talk about the basics, I am referring to elements such as variables, different kinds of data types, various operators one can use, conditional statements, arrays that store multiple values, functions for tasks execution, objects, which are collections of properties and events, among other fundamental concepts.

Understanding these ideas well is necessary for moving through React correctly, because you use them at each stage when creating applications with React.

2. The Spread operator

The Spread Operator came in JavaScript with ES6. It takes something you can iterate over and turns it into separate elements.

In React, the spread operator is often used to copy object values into another one while updating state so that it combines both objects' properties. See this syntax:

const [person, setPerson] = useState({

    id: '',

    name: '',

    age: ''

});

 setPerson([

            ...person,

            {

                id:"1",

                name: "Steve",

                age:"25"

            }

        ]);

In the example given before, a person duplicates every value from the person object into a new state object. This is then changed by adding other unique values that have identical properties, leading to an update of the state object.

This is among the various applications for the spread operator within React. When your application grows in size, utilizing tools such as the spread operator is beneficial to manage data more effectively and with greater efficiency.

3. The Ternary Operator

The ternary operator serves as a brief, single-line conditional operator that can substitute for if/else statements. It proves handy for swiftly evaluating a condition when one needs to render an element, update the state, or show some text.

Let's compare how the Ternary Operator works with the If/Else statement:


Example of Ternary Operator

condition ? 'True' : 'False'

// Example of If/Else statement

if(condition) {

    'True'

}

else {

    'False'

}:
JavaScript concepts to learn before React; Source: Medium

4. Destructuring

Dismantling allows us to take out values from groups and frameworks, then put them into different variables in an easy and clear manner. We shall learn this through some programming examples.

// With Destructuring

const objects = ['table', 'iPhone', 'apple']

const [furniture, mobile, fruit] = objects

// Without Destructuring

const furniture = objects[0]

const mobile = objects[1]

const fruit = objects[2]

In the example before, by using destructuring, we save three lines and the code looks neater. Now we will look at a different example where we pass props in React by destructuring:


// With Destructuring Ex-1

function Fruit({apple}) {

    return (

        <div>

            This is an {apple}

        </div>

    )

}

// With Destructuring Ex-2

function Fruit(props) {

    const {apple, iphone, car} = props

    return (

        <div>

            This is an {apple}

        </div>

    )

}

// Without Destructuring

function Fruit(props) {

    return (

        <div>

            This is an {props.apple}

        </div>

    )

}

You can see that when you don't apply destructuring to your props, you must repeatedly use them.

Destructuring helps to make the code more tidy and allows us to avoid typing the word props each time we need a prop variable. You will discover additional aspects of destructuring as you begin creating applications with JavaScript and React.

5. Arrow Functions

Arrow functions allow us to create functions in a simple manner with shorter syntax.

// Regular Functions

function hello() {

    return 'hello'

}

// Arrow Functions

let hello = () => 'hello'

The two operations from the earlier piece of code are doing identical tasks, yet you will observe that the arrow function appears neater and is more concise. The parentheses there contain space for parameters. Even if there are no arguments, these brackets should be present.

But if the function has only one argument, you can leave out these brackets:

let square = num => num * num

In arrow functions that are only one line, you don't need to write the return statement. For an arrow function with more lines, use curly braces {} like in normal functions.

let square = num => {

    return num * num

}

6. Array methods

In making applications with React, especially those of medium or large size, it is usual to use various array methods. In nearly every project you create using React, some kind of array method will be employed.

Spend some time understanding these techniques. The map() function, for example, is widely used. When you retrieve data from an outside source for display on the user interface, you always apply the map() function.

Other ways exist too, like filtering, reducing, sorting out, checking for inclusion, finding things, and doing something with each item in turn. Also adding or removing items from the end and beginning of lists, among other actions.

Many of them we use often, while others are seldom needed. It's important to know the frequently used array methods well and just recognize that other methods exist. This way, when you require those less common ones, you can learn them rapidly.

7. Async/Await

Async/Await feature gives a nicer, more tidy method to handle Promises. JavaScript works in a synchronous way and async/await lets us compose functions using promises as though they are synchronous, by pausing the running of additional code until the promise gets settled or refused.

To get it functioning, you must put the async word in front of a function declaration. Like this: async function promise() {}. Putting async before a function means that the function will always return a promise.

Within a function marked as async, the await keyword lets you pause the continuation of code until the promise is either fulfilled or not accepted. It's only possible to use await inside an async function.

Now, let's quickly finish off this section with an example:

async function asyncFunction() {

    let promise = new Promise(resolve => {

        resolve();

    });

Let the response be obtained after waiting for the promise; the following actions will halt until we know if the promise has been fulfilled or not.

    return console.log(response);

}

8. Promises

In modern JavaScript, you manage tasks that happen at the same time by using promises. When you make a promise in JavaScript, it might work out or not; this is called being resolved or rejected according to the language's terms.

There are 3 states of a promise:

  • Pending: when the final result of the promise is yet to be determined.
  • Resolved: When the promise is successfully resolved
  • Rejected: When the promise is rejected.

When a promise is resolved or rejected, you can apply the.then() or .catch() methods to it.

The .then() method gets activated when a promise is settled, either resolved or rejected. It accepts two functions that act as callbacks. When the promise is fulfilled and we get the outcome, that's when the first one happens. If, by chance, the promise does not work out, there's another choice we can use.

The catch() method acts as an error handler, getting called when the promise faces rejection or encounters a problem during execution.

let promise = new Promise((resolve, reject) => {

  const i = "Promise";

If i equals "Promise", then resolve; otherwise, reject. To grasp the syntax more clearly, refer to the previous section on Ternary Operators.

  }

);

promise.

    then(() => {

        console.log('Your promise is resolved');

    }).

    catch(() => {

        console.log('Your promise is rejected');

    });

9. The Fetch API

The Fetch API lets us send async requests to web servers from the browser and gives back a promise each time we make a request, which we use to get the response.

A simple fetch() function requires only one input, which is the URL of the resource you are trying to get. After that, it gives back a new promise that will be fulfilled with an object called Response when it is done. This Response object is the representation of the HTTP response.

To obtain the JSON content from this promise, one must apply the .json() method to the Response object. Subsequently, this will yield another promise that is fulfilled with the outcome of parsing JSON data found within response body.

It might be a little confusing, so pay close attention to the example below:

fetch('http://example.com/books.json') // fetching the resource URL

  .then(response => response.json()); // calling the.json() method on the promise

  .then(data => setState(data)); // updating the state with the JSON data

10. ES modules and Import/Export

JavaScript added modules in ES6, where each file acts as its own module. You are able to transfer items like objects, variables, lists and functions from one document to another. This process is known as importation and exportation of modules.

In the React framework, we utilize ES6 module system to separate components into distinct files. We export each component from its own file and then import it into another file where it needs to be displayed on the screen. Let's learn this with an example:


function Component() {

    return(

        <div>This is a component</div>

    )

}

export default Component

import Component from './Component'

function App() {

    return (

        <Component />

    )

}

In React, you have to render every component you declare in the App.js component.

In the previous example, we made a component named Component and exported it using this code: export default Component. After that, in App.js file, we import the Component like this: import Component from './Component'.

React; Source: GeeksforGeeks

Conclusion

JavaScript is a strong language, and maybe you did not catch some ideas when studying basic JavaScript. But if you want to be good at Reactjs development, it's important that you learn these JavaScript concepts well, along with many others.