From JavaScript to React

So you have been using JavaScript in the past, and you are pretty good at it, and you decided to take on React because that’s where everyone’s at. This article will give you some core concepts you need to know when you embark on this new journey.

React is a powerful and popular JavaScript library for building user interfaces. It has gained immense popularity in recent years, especially in the web development community, due to its component-based architecture and efficient rendering process. It allows developers to build complex UIs in a declarative and maintainable way.

However, mastering React can be a daunting task, especially if you’re new to the library or coming from a JavaScript background. We’ll cover ten core JavaScript concepts that are crucial for building React applications and some common mistakes people make when using them.

Concept 1: State and Props

State and props are the two most important concepts in React. State is used to store data that can change over time, while props are used to pass data from one component to another. A common mistake is modifying state directly, which can cause unexpected behavior. Instead, state should be updated using the update state method. I have an earlier article on useState, and I will have another article on “props” in the near future.

Concept 2: Arrow Function

Arrow functions are a shorthand syntax for writing functions in JavaScript. They are commonly used in React components as event handlers and callback functions.

const function = () => {
...
}

Concept 3: Destructuring

Destructuring is a feature in JavaScript that allows you to extract values from arrays and objects. It is commonly used in React to extract props and state variables.

function MyComponent(props) {
  const { name, age } = props;

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}

A common mistake is trying to destructure a value that is undefined. This can be fixed by providing a default value or checking if the value exists before destructuring.

Concept 4: Spread Operator

The spread operator is used to spread the contents of an array or object into a new array or object. It is commonly used in React to pass props to child components.

function MyComponent(props) {
  const { name, age, ...otherProps } = props;

  return (
    <ChildComponent name={name} age={age} {...otherProps} />
  );
}

A common mistake is trying to spread a value that is not an array or object. This can be fixed by checking the type of the value before spreading it. To learn more about spread operator I have created an article about it and you can find it here.

Concept 5: Template Literals

Template literals are a feature in JavaScript that allows you to embed expressions inside a string using backticks. They are commonly used in React to generate dynamic content.

function MyComponent(props) {
  const { name, age } = props;

  return (
    <p>{`My name is ${name} and I am ${age} years old.`}</p>
  );
}

A common mistake is not using backticks when defining a template literal. This will cause the expression to be treated as a string literal.

Concept 6: Conditional Rendering

React conditional rendering is a technique used to selectively render elements in a React component based on a condition or set of conditions. This is a powerful feature of React that allows developers to create dynamic and responsive user interfaces.

In functional components, conditional rendering is typically accomplished using JavaScript’s ternary operator, which is a shorthand way of writing an if-else statement. Here’s an example:

import React from 'react';

function Greeting(props) {
  return (
    <div>
      {props.isLoggedIn ? (
        <h1>Welcome back!</h1>
      ) : (
        <h1>Please log in.</h1>
      )}
    </div>
  );
}

export default Greeting;

In this example, the Greeting component takes a isLoggedIn prop and renders a different message depending on its value. If isLoggedIn is true, the component renders a “Welcome back!” message, and if it’s false, it renders a “Please log in.” message.

One common mistake when using conditional rendering is to forget to add the parentheses around the expressions to be rendered. This can result in syntax errors or unexpected behavior. Another mistake is to use complex conditions that can make the code difficult to read and maintain.

Concept 7: Closures

Closures are a fundamental concept in JavaScript, which are important for understanding how React works. A closure is created when a function returns another function and the returned function has access to the variables in the outer function’s scope. Closures are used in React to manage state and event handlers. A common mistake with closures is that developers forget to use the useCallback hook to memorize their event handlers, resulting in unnecessary re-renders.

function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    setCount(count + 1);
  };
  return (
    <div>
      <p>{count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

In this example, handleClick is a closure that has access to the count variable in the Counter component’s scope.

Concept 8: Higher-Order Functions

Higher-order functions are functions that take other functions as arguments or return functions as values. They are commonly used in React for reusability and composability. A common mistake with higher-order functions is that developers forget to handle errors when passing functions as arguments or returning functions.

function withAuth(WrappedComponent) {
  return function Authenticated(props) {
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    useEffect(() => {
      // authenticate user
      setIsLoggedIn(true);
    }, []);
    if (!isLoggedIn) {
      return <p>Please log in to access this page</p>;
    }
    return <WrappedComponent {...props} />;
  };
}

In this example, withAuth is a higher-order function that takes a component as an argument and returns a new component with authentication logic.

Concept 9: Event Loop

The event loop is a core concept in JavaScript that governs how asynchronous operations are handled. Understanding the event loop is important for React developers to write performant code. A common mistake with the event loop is that developers block the main thread by performing heavy computations, which can cause the UI to freeze.

function computeFactorial(n) {
  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}

In this example, computeFactorial is a function that performs a heavy computation, which can block the main thread.

Concept 10: React Router

React Router is a library for declarative routing in React applications. It is important for building complex single-page applications with multiple views. A common mistake with React Router is that developers forget to handle edge cases, such as invalid routes or unauthorized access.

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/about" component={About} />
        <PrivateRoute exact path="/dashboard" component={Dashboard} />
        <Route component={NotFound} />
      </Switch>
    </Router>
  );
}

In this example, PrivateRoute is a custom component that ensures that the user is authenticated before rendering the Dashboard component. We’ll have a closer look at React routing and private routing in a future article.

You Might Also Like