Introduction to React's basic concepts

Photo by Farzad on Unsplash

Introduction to React's basic concepts

React is a Javascript library used in building user interfaces. It is open-source and primarily maintained by Meta.

React can be used to build single-page web applications and mobile applications. It simplifies the development process by allowing you to break your code into small, reusable bits called components, which reduces the amount of code it would typically take if you were building with vanilla Javascript.

Before learning React, you must have a solid knowledge of HTML and CSS and at least the basics of Javascript. Because React is a Javascript library, having a grasp of Javascript is important if you intend to learn React quickly and efficiently.

In the next section, we will discuss some additional concepts in Javascript needed to have a smooth sail in React.

Javascript concepts needed for React

In this section, we will briefly discuss some Array methods, ES6 modules, spread and rest operators, Destructing, template literals, and ternary operators.

Array Methods

These are inbuilt Javascript functions; we can use these functions to perform certain actions on an array.

Map method

This method is used to modify the contents of an array. It runs the callback function for each element in the array. This method loops through an existing array and returns a new array containing the modified values.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const newNumbers = numbers.map((num) =>  num * 5)
console.log(newNumbers) // [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

It is important to note that this method does not modify the original array.

Reduce method

This method executes a reducer function for all items in the array. It returns one value—the accumulation of the function's results. It also doesn’t modify the original array.

 const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 const sum = numbers.reduce((acc, curr) =>  acc + curr, 0)
 console.log(sum) // 55

As seen in the code snippet above, the reducer function accepts two parameters. The first is the initial value, which in our case is 0, but if no initial value is passed, the first element in the array is used instead.

The second is the current value; the first time the reducer runs, the value would be the first item in the array if an initial value is supplied; otherwise, it would be the second item in the array.

Filter method

This method loops through an existing array, and depending on the condition passed into the method, it returns a new array with values matching that condition.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const greaterThanFive = numbers.filter((num) =>  num > 5)
console.log(greaterThanFive) // [6, 7, 8, 9, 10]

As seen above, the condition requires that the values be greater than 5, so the new array only contains values greater than 5.

You can use this method on any data type, not just numbers. However, since it is an array method, this data type has to be a value contained in an array.

Find method

This method, just like the filter method, loops through an existing array and returns a single value depending on the condition passed into the method.

  const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  const lessThanFive = numbers.find((num) =>  num < 5)
  console.log(lessThanFive) // 1

The major difference between this method and the filter method is that it returns one value—the specific array item if it can find it; otherwise, it returns undefined, not a new array.

If more than one value in the array passes the condition, it returns only the first value.

ForEach method

This method loops through an array and calls the function passed as a parameter for every item in that array. It returns undefined.

let sum = 0 
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.forEach((num) => {
     sum += num
  })
console.log(sum) // 55

In the code snippet above, we are getting the sum of all the elements in the array by looping over the array and adding the current element to the sum variable. This method is quite similar to a for loop.

ES6 Modules

With modules, you can break your code into small bits and use them across files in your project. This makes your code easier to manage and more reusable.

To effectively use modules, you need to know how to use the import and export keywords.

Export

You can export your class, variable, or function from the file it was created in. Exporting your code allows you to use it in other files, resulting in reusability.

There are two types of exports: Default and Named exports.

  • Default export: This is the main bit of code exported from a file; a file cannot have more than one default export. To create a default export, you have to use the export and default keywords together while exporting the code.

      const sumFunc = (arr) => {
        return arr.reduce((acc, current) => acc + current, 0)
      }
      export default sumFunc
    
  • Named export: While a file can only include one default export, it can have various named exports. To create a named export, you only need to add the export keyword to that piece of code while exporting.

      export const name = "Chiamaka"
      export const age = 26
    

    Or you can export all named exports in the file on the same line of code using curly braces.

      const name = "Chiamaka"
      const age = 26
      export { name, age }
    

Import

To use a piece of code in a file other than the one it was created in, it needs to be imported. Please note that if the code is not exported from its parent file, it cannot be imported.

The way a module is imported depends on how it was exported—if it was exported as a default or named export.

To import a default export, you use the import keyword and the name of the bit of code you are to import—a variable, function, or class. Let us import the sumFunc we created earlier

import sumFunc from 'name-of-parent-file'
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sumFunc(numbers)

You have to add curly braces when importing a named export. Let’s import the person and age variables.

import { name, age } from 'name-of-parent-file'
console.log(name) // Chiamaka
console.log(age) // 26

Please ensure you are importing from the correct file location in your project’s directory, so you don’t get an error.

Rest and Spread Operators

These operators have the same syntax—three dots—but they work differently, and are used in different contexts.

Spread Operator

With the spread operator, you can copy certain elements of an already existing array or object into a new one.

const lessThanFive = [1, 2, 3, 4]
const greaterThanFive = [6, 7, 8, 9, 10]
const allNumbers = [...lessThanFive, ...greaterThanFive]
console.log(allNumbers) // [1, 2, 3, 4, 6, 7, 8, 9, 10]

This operator spreads an iterable into individual entities. You can also use it on objects

const studentInfo = {name: "chelsea", dob: 2010, class: "JS3"}
const additionalInfo = {age: 13, height: 6.5}
const updatedStudentInfo = {...studentInfo, ...additionalInfo}
console.log(updatedStudentInfo) //{name: "chelsea", dob: 2010, class: "JS3", age: 13, height: 6.5}

Rest operator

This operator is used a bit differently; it is passed as a parameter to a function so that the function can accept an indefinite number of arguments as an array.

If you use this operator, the function will run for all the arguments passed into it. A function can only contain one rest operator.

function getSum(...numbers) {
  let sum = 0;
  for (let num of numbers) {
    sum += num;
  }
  return sum;
}
console.log(getSum(2,4,6)) // 12
console.log(getSum(1,3,5)) // 9
console.log(getSum(1,2,3,4,5,6,7,8,9,10)) // 55

To understand how the rest operator is used in function calls, read about the arguments object in Javascript.

Since the syntax of both operators is the same, the best way to differentiate between them is how they are used. If you see three dots in a function’s parameter, it is a rest operator. Also, they work in opposite ways: the spread operator can be used to expand an iterable, while the rest operator is used to compress.

Template Literals and Ternary Operators

Template Literals

When using template literals, you define a string with backticks `` instead of quotes, and you can use both single and double quotes in the sentence without escaping them.

What’s more interesting about template literals is that you can use them to embed variables or expressions into your string. This method is called string interpolation.

const name = "Chiamaka"
const jobTitle = "frontend developer"
const bio = `${name} is a ${jobTitle}`
console.log(bio) // Chiamaka is a frontend developer

Ternary Operators

These operators are a shorter way to write conditional statements. It evaluates two expressions and returns a value based on the condition.

const premium = true
const price = premium ? 100 : 50
console.log(price) // 100

As seen above, it takes a condition—whatever is before the question mark—and if the condition is true, the first value is returned; otherwise, the second value is returned.

Destructing assignment

With destructuring, you can extract individual values from an array or object into variables.

Destructing Arrays

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const [a, b] = numbers;
console.log(a) // 1
console.log(b) // 2

Please note that variables are set from right to left, so the first variable is assigned to the item at array[0], the second variable to the array's second item, etc.

To skip items in an array, we use a comma

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const [a, ,b] = numbers;
console.log(a) // 1
console.log(b) // 3

You can skip as many values as you want in an array by using multiple commas, one for each value you want to skip.

Destructing Objects

To destructure an object, curly braces {} is used instead of square brackets [], and you use the property key as your variable name.

const profile = {
  name: "Chiamaka",
  jobTitle: "Frontend developer",
  age: 26,
};
const { name, jobTitle } = profile;
console.log(name) // Chiamaka
console.log(jobTitle) //Frontend developer

Creating a new React app

There are various ways to create a React app, but command-line interface (CLI) tools simplify the process. When using CLI tools, you won’t need to use bundlers or compilers like Webpack and Babel.

We would discuss two of these CLI tools: Create React App (CRA) and Vite.

CRA

This tool sets up your development environment, installing all the packages you need to get your React project running in their latest versions so that the packages used in your app are not obsolete. However, you would need a Node JS version higher than 14.0 installed on your device for it to work.

To create a react app with CRA, copy the command below

npx create-react-app your-app-name

Vite

This tool, just like CRA, sets up your development environment and installs all the packages needed for your app to run. However, it is significantly faster than CRA, and it can also be used to set up new projects in Vanilla Javascript or other Javascript frameworks like Vue, Preact, etc.

To create a react app with Vite using npm, copy the command below and follow the prompt

npm create vite@latest

React Components

React components can be simply defined as blocks of code. Ideally, each code block should handle its logic and appearance, so a component should include both its markup (HTML), style (CSS), and logic (Javascript).

You can also think of components as Javascript functions or classes that return markup.

There are two types of components in React: class components and functional components.

Class components

These are components created with Javascript classes; they extend React’s Component class. They were initially referred to as stateful or smart components because they handled their state, and React lifecycle methods could be used in them.

import React, { Component } from 'react'

class Welcome extends Component {
  render() {
    return <h1>Hello there</h1>;
  }
}

export default Welcome

When writing class components, you rely a lot on this keyword in Javascript. You use this to consume the component’s props and define its state. We will discuss props and state in the next section.

Functional components

These are components created with Javascript functions; these can be either arrow functions or functions created with the function keyword.

They were initially referred to as stateless or dumb components because they couldn’t handle their state, but since React 16.8, they can handle their state and use lifecycle methods via React hooks.

import React from 'react'

const Welcome = () => {
  return <h1>Hey there</h1>;
};
export default Welcome

There’s no need to use this keyword in functional components.

Since the release of React Hooks, functional components have become the preferred method for creating components in React.

State and Props in React

State and Props are both objects in React that contain information regarding a component.

State

A state is an object that contains properties declared within your component. It is your component’s memory, and any update to this memory causes React to re-render your component, ensuring that your UI remains consistent with these changes.

In class components, state is declared using this keyword.

import React, { Component } from 'react'

 class Welcome extends Component {
  constructor() {
    super();
    this.state = {
      message: "Hello there",
      name: "Chiamaka",
    };
  }
  render() {
    return (
      <h1>
        {this.state.message}, {this.state.name}
      </h1>
    );
  }
}
 export default Welcome

In functional components, we make use of the useState hook to declare a state.

import React, { useState } from 'react'

const Counter = () => {
  const [count, setCount] = useState(0);
  return <p>{count}</p>;
};

export default Counter

Props

This is short for properties, and it is an object that contains properties passed into your component; they are similar to attributes in HTML and are essentially used to pass data from one component to another.

Props are passed into components in the same way attributes are passed into HTML elements.

import Welcome from "./Welcome.js";
const HomePage = () => {
  return (
    <div>
      <Welcome name="Chiamaka" />
    </div>
  );
};
export default HomePage;

To access props passed into a class component, you use this keyword

import React, { Component } from 'react'

 class Welcome extends Component {
 constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>
        Hey there, {this.props.name}
      </h1>
    );
  }
}
 export default Welcome

Props in functional components can be accessed in two ways: you pass props as an argument to your function.

const Welcome = (props) => {
  return (
      <h1>Hey there, {props.name}</h1>
    );
 };

export default Welcome

Or you could destructure the props object and use individual values.

const Welcome = ({name}) => {
  return (
      <h1>Hey there, {name}</h1>
    );
 };

This method is less cumbersome

Learning React can be a daunting task. However, once you have an understanding of these concepts the process becomes easier. For an in-depth explanation of these concepts, please see the official React docs