JavaScript concepts you should know before learning React

Having a solid understanding of Javascript concepts plays an important role in building React applications that are easier to maintain and debug.

· 4 min read
Mary Maina

Mary Maina

I am a frontend engineer passionate about building intuitive user interfaces. Tools: React, Next.JS, TypeScript, React Native, NodeJs

Understanding JavaScript concepts is essential before starting your journey to learn React.js.React is a free and open-source front-end JavaScript library for building user interfaces based on components that has revolutionized web development. A solid foundation and mastery of JavaScript concepts facilitates learning and it enables you to build robust React applications that adhere to best practices.

To use React capabilities effectively, understanding these core JavaScript concepts is important.

Higher Order functions

Higher-order functions are functions that either take other functions as arguments or return functions as their results. In JavaScript, functions are first-class citizens. This means they can be passed as arguments, assigned to variables, and returned from other functions.

JavaScript methods like map(), filter(), and reduce() are fundamental concepts used in React.js applications to render a list, filter data, and aggregate data.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers); // Output: [2, 4, 6, 8]

In React HOCs allow you to add functionality to a component without modifying the code.

import React from 'react';

// Higher-order component that adds a loading indicator to a component
function withLoadingIndicator(Component) {
  return function WithLoadingIndicator(props) {
    const { isLoading} = props;
    if (isLoading) {
      return <div>Loading...</div>;
    }
    return <Component />;
  };
}

// Component to be enhanced with loading indicator
function EnhancedComponent() {
  return <div>Display the data  after loading inicator</div>;
}

// Using the higher-order component with the component
const ComponentWithLoading = withLoadingIndicator(EnhancedComponent);

// Usage in a parent component
function ParentComponent() {
  return <ComponentWithLoading isLoading={true} />;
}

Asynchronous JavaScript

Asynchronous JavaScript plays a crucial role in React applications, because it helps manage operations that depend on external data sources or take time to complete, such as API requests. Asynchronous JavaScript entails callbacks, promises, and async/await, allowing you to handle API calls.

Example of using async/await

async function fetchData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const data = await response.json();
  console.log(data);
}

fetchData();

React applications often need to fetch data from an API. Asynchronous JavaScript, using fetch, axios, or other HTTP clients, is used to handle these operations. useEffect is used to handle API calls, a side effect in a React app.

Here is an example

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

function Users() {
  const [data, setData] = useState([]);

  useEffect(() => {
    async function fetchUsers() {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      const result = await response.json();
      setData(result);
    }

    fetchUsers();
  }, []); // The empty array ensures this effect runs only once after the initial render

  return (
    <div>
      {data?.length > 0 &&<div>{JSON.stringify(data)}</div> }
    </div>
  );
}
export default User

ES6+ Concepts

ECMAScript 2015, also known as ECMAScript 6 (ES6) introduced new features to JavaScript that significantly enhanced the language’s capability and improved the development experience. These features play an important role in React development, where modern JavaScript patterns are common.

Here are some key ES6 features: template literals, arrow functions, let and const, spread operator, destructuring, module(export/import), and classes. a more detailed example that showcases how several ES6 features are commonly used in a React application.

Here is an example that showcases how some of the ES6 concepts are used in the React ecosystem.

Directory Structure

  • src/
    • components/
      • UserList.js
    • App.js
    • index.js

This is the main component where we import the UsersList component.

import React, { useState } from 'react';
import UserList from './components/UserList';

const App = () => {
  // useState to manage state in a functional component
  const [users, setUsers] = useState([
    { id: 1, name: 'John Doe', email: 'john@example.com' },
    { id: 2, name: 'Mark Doe', email: 'mark@example.com' }
    { id: 3, name: 'Jane Doe', email: 'jane@example.com' }
  ]);

  return (
    <div>
      <h1>User Directory</h1>
      <UserList users={users} />
    </div>
  );
};

export default App;

The UsersList component will display a list of users. We'll use some of the Es6 concepts like destructuring and arrow functions.

import React from 'react';

//Destructured props
const User = ({ user }) => {
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Email: {user.email}</p>
    </div>
  );
};

// An arrow function
const UserList = ({ users }) => {
  return (
    <div>
      {users.map(user => <User key={user.id} user={user} />)}
    </div>
  );
};

export default UserList;

Arrays and Objects

Arrays and objects are JavaScript data structures that are used extensively in React for managing and manipulating data. Knowing how to work with these data structures is vital in React development.

Arrays in JavaScript

Arrays are used to store multiple values in a single variable. Here are some of the common operations you performed on arrays:

  • Access: Retrieve elements from the array using their index.
  • Manipulation: Methods like push(), pop(), shift(), unshift(), and splice() change arrays.Objects in JavaScript

Objects in JavaScript

Objects represent a collection of properties, used to store key-value pair collections of various data and more complex entities. In JavaScript, objects can be created using literal notation or constructors.

  • Creation: { name: 'Alice', age: 25 }
  • Access: Using dot notation (obj.name) or bracket notation (obj['name']).
  • Manipulation: Adding, modifying, or deleting properties.

Arrays and Objects React

In React, arrays and objects often can be used together, especially when dealing with lists of data objects. Consider this component managing a list of user objects:

import React, { useState } from 'react';

const UserList = () => {
  const [users, setUsers] = useState([
    { id: 1, name: 'Alice', age: 25 },
    { id: 2, name: 'Bob', age: 30 }
  ]);

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          {user.name} - Age: {user.age}
        </li>
      ))}
    </ul>
  );
};

export default UserList;


share

Mary Maina

I am a frontend devloper