Skip to content

React 101

!!! info "About" This is my personal documentation about React - a quick reference guide for getting started and understanding core concepts.

Introduction

React is a JavaScript library for building user interfaces. It allows developers to create reusable UI components and manage the state of their applications efficiently.


Getting Started

!!! tip "Prerequisites" Make sure you have Bun installed on your machine before proceeding.

Create a new React application using Vite:

bun create vite@latest

Then follow the prompts to set up your project!


Core Concepts

🧩 Components

Components are the building blocks of a React application. They are reusable pieces of UI that can be functional or class-based. Modern React favors functional components.

// Simple functional component
function Welcome() {
  return <h1>Hello, World!</h1>;
}

// Component with props
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

📝 JSX

JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. It makes React code more readable and intuitive.

const name = "React";
const element = <h1>Hello, {name}!</h1>;

📦 State & Props

State is used to manage data within a component, while Props are used to pass data from parent to child components.

import { useState } from 'react';

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

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

🔄 Lifecycle & Effects

In React, the lifecycle refers to the series of phases a component goes through from its creation to its removal from the UI. Understanding the lifecycle is crucial for controlling what happens at specific moments, like fetching data, updating the UI, or cleaning up resources.

Lifecycle Phases: - Mounting - Component is being created and inserted into the DOM - Updating - Component is being re-rendered due to state or prop changes - Unmounting - Component is being removed from the DOM

!!! note "Modern React" With React Hooks, you typically use useEffect() instead of traditional class lifecycle methods.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    // This runs after every render where count changes
    document.title = `You clicked ${count} times`;

    // Optional cleanup function
    return () => {
      console.log('Cleanup on unmount or before next effect');
    };
  }, [count]); // Dependency array

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

🎯 Handling Events

Handling events in React is similar to handling events in regular HTML, but with some syntactic differences (camelCase naming, passing functions as handlers).

function ClickButton() {
  function handleClick(e) {
    e.preventDefault();
    alert('Button clicked!');
  }

  return <button onClick={handleClick}>Click me</button>;
}

🔀 Conditional Rendering

React allows you to render different components or elements based on certain conditions using JavaScript operators.

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

📋 Lists and Keys

Render lists of elements using the map() function. Each element in the list must have a unique key prop for React's reconciliation process.

function NumberList({ numbers }) {
  return (
    <ul>
      {numbers.map((number) => (
        <li key={number.toString()}>
          {number}
        </li>
      ))}
    </ul>
  );
}

📝 Forms

Handling forms in React involves managing the state of form elements and responding to user input. Libraries like react-hook-form simplify form management.

import { useForm } from 'react-hook-form';

function MyForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input 
        {...register("firstName", { required: true })} 
        placeholder="First Name"
      />
      {errors.firstName && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

Quick Reference

Concept Purpose
Components Building blocks of UI
JSX HTML-like syntax in JavaScript
State Internal component data
Props Data passed between components
Hooks Reusable stateful logic (useState, useEffect, etc.)
Events Handle user interactions
Conditional Rendering Display different UI based on conditions
Lists & Keys Render collections of elements
Forms Manage user input

!!! tip "Next Steps" - Explore React Router for navigation - Learn about Context API for global state - Try state management libraries like Zustand or Redux - Build a small project to practice these concepts!

Object Rendring

Array Rendring

Array Object Rendring

Data Fetching with useEffect