No history yet

Introduction to React

What Is React?

React is a JavaScript library for building user interfaces. Created by Facebook, its main job is to make it easier to create interactive UIs by breaking them down into small, reusable pieces. Instead of managing a whole page at once, you build isolated bits of logic and design called components.

Think of it like building with LEGO bricks. Each brick is a component, and you combine them to create a complex structure, like a web page.

This component-based approach makes your code cleaner, easier to manage, and scalable. You can build a button component once and use it everywhere in your application, and if you need to change the button's style, you only have to update it in one place.

Lesson image

Components, State, and Props

Components are the heart of React. They are essentially JavaScript functions that return HTML-like code describing what should appear on the screen. Here’s a simple Welcome component:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

Notice the props.name part? props (short for properties) are how you pass data into a component, similar to how arguments are passed to a function. They allow you to create dynamic and reusable components. You would use the Welcome component like this:

const element = <Welcome name="Sara" />;

This would render <h1>Hello, Sara</h1> on the page. Props flow in one direction: from parent components down to child components. They are read-only, meaning a component can't change its own props.

But what if a component needs to manage its own data that changes over time, like a counter that increments when you click a button? For that, we use state.

State

noun

A built-in React object that is used to contain data or information about the component. A component’s state can change over time; whenever it changes, the component re-renders.

Here's how you'd use the useState Hook to add state to a functional component:

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>
  );
}

In this example, useState(0) initializes our count state to 0. When the button is clicked, setCount(count + 1) is called. This updates the count state, and React automatically re-renders the Counter component to display the new value.

JSX and the Virtual DOM

The HTML-like syntax you saw in the examples is called JSX, which stands for JavaScript XML. It's a syntax extension that lets you write what looks like HTML directly within your JavaScript code. While you don't have to use it, JSX makes writing React components much more intuitive.

Under the hood, JSX is converted into regular JavaScript function calls. For example, this JSX code:

const element = <h1 className="greeting">Hello, world!</h1>;

Is compiled into this:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

This leads to one of React's most powerful features: the Virtual DOM. Directly manipulating the browser's DOM (the tree structure of your webpage) is slow. React creates a lightweight copy of the DOM in memory, called the Virtual DOM.

When a component's state changes, React first updates the Virtual DOM. Then, it compares the updated Virtual DOM with a snapshot of the Virtual DOM from before the change. This comparison process is called "diffing." React identifies exactly what changed and then updates only those specific parts of the real DOM. This selective updating is much faster than re-rendering the entire page, which is why React applications feel so fast and responsive.

The Component Lifecycle

Every React component goes through a series of phases known as its lifecycle. There are three main phases:

  1. Mounting: The component is created and inserted into the DOM.
  2. Updating: The component re-renders because its props or state have changed.
  3. Unmounting: The component is removed from the DOM.

In modern React, we manage these lifecycle events using Hooks. The most common one is the useEffect Hook. It lets you perform "side effects" in your components, such as fetching data from an API, setting up a subscription, or manually changing the DOM.

Here’s a simple example:

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

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

By default, useEffect runs after the first render and after every update. You can also control when it runs by passing an array of dependencies, allowing you to fine-tune when your side effects occur.

Understanding these core concepts—components, props, state, JSX, and the virtual DOM—provides a solid foundation. With this knowledge, you're ready to start building powerful and efficient web applications with React.

Quiz Questions 1/6

What is the primary purpose of React?

Quiz Questions 2/6

In React, how is data passed from a parent component to a child component?