React Documentation

A JavaScript library for building user interfaces - Create modern, interactive web applications

Introduction to React

React is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

React 18 is the latest major version, introducing concurrent features, automatic batching, and the new root API.

Setup & Installation

Create React App

The easiest way to get started with React is using Create React App.

# Install Create React App
$ npx create-react-app my-app

# Navigate to project directory
$ cd my-app

# Start development server
$ npm start

Project Structure

my-app/
├── node_modules/
├── public/
│   ├── index.html
│   ├── favicon.ico
│   └── manifest.json
├── src/
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   └── reportWebVitals.js
├── package.json
└── README.md

JSX

JSX is a syntax extension for JavaScript. It looks similar to HTML but it's actually JavaScript under the hood.

Basic JSX

const element = <h1>Hello, World!</h1>;

Embedding Expressions

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

JSX Attributes

const element = <img src="profile.jpg" alt="Profile Picture" />;

Components

Components are the building blocks of React applications. They let you split the UI into independent, reusable pieces.

Function Components

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

// Using the component
<Welcome name="John" />

Class Components

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

// Using the component
<Welcome name="John" />

Component Composition

function App() {
  return <div>
    <Welcome name="John" />
    <Welcome name="Jane" />
    <Welcome name="Bob" />
  </div>;
}

Props & State

Props (Properties)

Props are read-only inputs to components. They allow data to flow from parent to child components.

function UserCard(props) {
  return <div className="user-card">
    <h2>{props.name}</h2>
    <p>Age: {props.age}</p>
  </div>;
}

// Default props
UserCard.defaultProps = {
  age: 18
};

State

State allows components to manage their own data that can change over time.

import React, { useState } from "react";

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

  return <div>
    <p>Count: {count}</p>
    <button onClick={
}setCount(count + 1)
    }>Increment</button>
  </div>;
}

Hooks

Hooks are functions that let you "hook into" React state and lifecycle features from function components.

useState

import React, { useState } from "react";

function Example() {
  const [state, setState] = useState("Initial value");
  
  return <div>
    <p>State: {state}</p>
    <button onClick={
}
setState("New value")
    }>Change State</button>
  </div>;
}

useEffect

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

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

  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {
    document.title = `Count: ${count`;
  }, [count]);

  return <button onClick={
}
setCount(count + 1)
}>Click {count} times</button>;
}

useContext

import React, { useContext } from "react";

// Create context
const ThemeContext = React.createContext("light");

function ThemedButton() {
  const theme = useContext(ThemeContext);
  
  return <button className={
theme === "dark" ? "dark-btn" : "light-btn"
}>Themed Button</button>;
}

useReducer

import React, { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return {
        count: state.count + 1
      };
    case "decrement":
      return {
        count: state.count - 1
      };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, {
    count: 0
  });

  return <div>
    <p>Count: {state.count}</p>
    <button onClick={
}
dispatch({
        type: "increment"
      })
    }>+</button>
    <button onClick={
}
dispatch({
        type: "decrement"
      })
    }>-</button>
  </div>;
}

Common Hooks

Hook Purpose
useState Add state to function components
useEffect Perform side effects in function components
useContext Access context in function components
useReducer Manage complex state logic
useCallback Memoize callbacks to prevent unnecessary re-renders
useMemo Memoize expensive calculations
useRef Access DOM elements or persist mutable values
useLayoutEffect Similar to useEffect but runs synchronously after DOM mutations

Events

React provides a synthetic event system that works across all browsers. Event names are camelCased instead of lowercase.

Basic Event Handling

function Button() {
  function handleClick() {
    console.log("Button clicked!");
  }

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

Event Object

function Input() {
  function handleChange(event) {
    console.log("Value:", event.target.value);
  }

  return <input 
    type="text" 
    onChange={
handleChange
}
 />;
}

Common Events

Event Description
onClick Mouse click
onChange Input value changed
onSubmit Form submitted
onKeyDown Key pressed down
onKeyUp Key released
onMouseEnter Mouse enters element
onMouseLeave Mouse leaves element
onFocus Element receives focus
onBlur Element loses focus

Routing

React Router is the standard routing library for React applications. It enables navigation between different components in a React application.

Install React Router

$ npm install react-router-dom

Basic Routing Setup

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";

function App() {
  return <Router>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/users">Users</Link>
    </nav>

    <Routes>
      <Route path="/" element={
}
Home />
      <Route path="/about" element={
}
About />
      <Route path="/users" element={
}
Users />
    </Routes>
  </Router>;
}

function Home() {
  return <h1>Home Page</h1>;
}

function About() {
  return <h1>About Page</h1>;
}

function Users() {
  return <h1>Users Page</h1>;
}

Route Parameters

<Route 
  path="/users/:id" 
  element={
}
UserDetail 
/>

function UserDetail() {
  const {
    params
  } = useParams();
  
  return <h1>User ID: {params.id}</h1>;
}

Navigation

import {
  useNavigate
} from "react-router-dom";

function LoginButton() {
  const navigate = useNavigate();

  function handleClick() {
    navigate("/dashboard");
  }

  return <button onClick={
handleClick
}
>Login</button>;
}

Practical Examples

Counter Application

import React, { useState } from "react";

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

  return <div>
    <h1>Counter: {count}</h1>
    <button onClick={
}
setCount(count + 1)
    }>Increment</button>
    <button onClick={
}
setCount(count - 1)
    }>Decrement</button>
  </div>;
}

export default Counter;

Todo List

import React, { useState } from "react";

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState("");

  function addTodo() {
    if (input.trim()) {
      setTodos([...todos, input]);
      setInput("");
    }
  }

  function removeTodo(index) {
    setTodos(todos.filter((_, i) => i !== index));
  }

  return <div>
    <h1>Todo List</h1>
    <input
      type="text"
      value={
input
}
      onChange={
e => setInput(e.target.value)
}

      placeholder="Add a new todo"
    />
    <button onClick={
addTodo
}
>Add</button>

    <ul>
      {todos.map((todo, index) => (
        <li key={
index
}
>
          todo
          <button onClick={
}
removeTodo(index)
          }>Remove</button>
        </li>
      ))}

    </ul>
  </div>;
}

export default TodoList;

Fetch API Data

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

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchUsers() {
      const response = await fetch("https://jsonplaceholder.typicode.com/users");
      const data = await response.json();
      setUsers(data);
      setLoading(false);
    }

    fetchUsers();
  }, []);

  if (loading) return <p>Loading...</p>;

  return <ul>
    {users.map(user => (
      <li key={
user.id
}
>{user.name}</li>
    ))}

  </ul>;
}

export default UserList;