โš›๏ธ

React

A JavaScript library for building user interfaces

v19.0.0IntermediateUIComponentsHooksVirtual DOMJSX

Overview

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.

Declarative views make your code more predictable and easier to debug. Component-based architecture lets you build encapsulated components that manage their own state, then compose them to make complex UIs.

React can also render on the server using Node and power mobile apps using React Native.

Hello World Component

App.tsx
1400">function 300">Welcome({ name }: { name: 400">string }) {
2 400">return <h1>Hello, {name}!</h1>;
3}
4 
5400">export 400">default 400">function 300">App() {
6 400">return (
7 <div>
8 <Welcome name="World" />
9 </div>
10 );
11}

Installation

Quick Install

Terminal
1-amber-400">npx create-react-app my-app --template typescript

Requirements

  • Node.js 18+
  • npm 9+ or yarn 1.22+

Setup Steps

  1. 1Install Node.js (v18 or higher recommended)
  2. 2Run: npx create-react-app my-app --template typescript
  3. 3Navigate to project: cd my-app
  4. 4Start development server: npm start
  5. 5Open http://localhost:3000

Components

Components are the building blocks of any React application. A component is a self-contained piece of UI that can be reused throughout your application.

React components can be written as functions or classes, but function components are now the standard approach.

Function Component

Button.tsx
1interface ButtonProps {
2 text: 400">string;
3 onClick: () => 400">void;
4 variant?: 'primary' | 'secondary';
5}
6 
7400">function 300">Button({ text, onClick, variant = 'primary' }: ButtonProps) {
8 400">return (
9 <button
10 onClick={onClick}
11 className={`btn btn-${variant}`}
12 >
13 {text}
14 </button>
15 );
16}

Hooks

Hooks let you use state and other React features without writing a class. They are functions that let you "hook into" React state and lifecycle features from function components.

The most commonly used hooks are useState, useEffect, useContext, and useRef.

useState Hook

Counter.tsx
1400">import { useState } 400">from 'react';
2 
3400">function 300">Counter() {
4 400">const [count, setCount] = 300">useState(0);
5 
6 400">return (
7 <div>
8 <p>You clicked {count} times</p>
9 <button onClick={() => 300">setCount(count + 1)}>
10 Click me
11 </button>
12 </div>
13 );
14}

useEffect Hook

UserProfile.tsx
1400">import { useState, useEffect } 400">from 'react';
2 
3400">function 300">UserProfile({ userId }: { userId: 400">string }) {
4 400">const [user, setUser] = 300">useState(400">null);
5 400">const [loading, setLoading] = 300">useState(400">true);
6 
7 300">useEffect(() => {
8 400">async 400">function 300">fetchUser() {
9 300">setLoading(400">true);
10 400">const response = 400">await 300">fetch(`/api/users/${userId}`);
11 400">const data = 400">await response.300">json();
12 300">setUser(data);
13 300">setLoading(400">false);
14 }
15
16 300">fetchUser();
17 }, [userId]); // Re-run when userId changes
18 
19 400">if (loading) 400">return <div>Loading...</div>;
20 400">return <div>{user?.name}</div>;
21}

JSX

JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code in your JavaScript files. JSX produces React elements that can be rendered to the DOM.

JSX is not required to use React, but it makes the code more readable and expressive.

JSX Expressions

Greeting.tsx
1400">function 300">Greeting({ isLoggedIn, user }) {
2 400">return (
3 <div>
4 {isLoggedIn ? (
5 <h1>Welcome back, {user.name}!</h1>
6 ) : (
7 <h1>Please sign in</h1>
8 )}
9
10 {/* Rendering lists */}
11 <ul>
12 {user.hobbies.300">map((hobby, index) => (
13 <li key={index}>{hobby}</li>
14 ))}
15 </ul>
16 </div>
17 );
18}

Best Practices

  • Use functional components with hooks instead of class components
  • Keep components small and focused on a single responsibility
  • Use TypeScript for better type safety and developer experience
  • Implement React.memo for expensive computations
  • Use keys properly when rendering lists
  • Avoid inline function definitions in JSX when possible
  • Use React DevTools for debugging
  • Implement error boundaries for better error handling

Common Pitfalls

โš ๏ธMutating state directly instead of using setState
โš ๏ธMissing dependencies in useEffect dependency array
โš ๏ธCreating unnecessary re-renders
โš ๏ธUsing index as key for dynamic lists
โš ๏ธNot handling loading and error states
โš ๏ธOver-fetching data in useEffect

Recommended File Structure

React Project
3 items
src
components
Button.tsx
Card.tsx
Header.tsx
hooks
useAuth.ts
useFetch.ts
pages
Home.tsx
About.tsx
App.tsx
index.tsx
package.json
tsconfig.json

Code Snippets

Basic useState

basic

Simple counter with useState hook

TSX
1400">const [count, setCount] = 300">useState(0);
2 
3<button onClick={() => 300">setCount(prev => prev + 1)}>
4 Count: {count}
5</button>

Data Fetching with useEffect

intermediate

Fetch data on component mount

TSX
1400">const [data, setData] = 300">useState(400">null);
2400">const [loading, setLoading] = 300">useState(400">true);
3 
4300">useEffect(() => {
5 300">fetch('/api/data')
6 .300">then(res => res.300">json())
7 .300">then(data => {
8 300">setData(data);
9 300">setLoading(400">false);
10 });
11}, []);

Custom Hook

advanced

Reusable custom hook pattern

TSX
1400">function useLocalStorage<T>(key: 400">string, initialValue: T) {
2 400">const [storedValue, setStoredValue] = useState<T>(() => {
3 400">try {
4 400">const item = window.localStorage.300">getItem(key);
5 400">return item ? JSON.300">parse(item) : initialValue;
6 } 400">catch {
7 400">return initialValue;
8 }
9 });
10 
11 400">const setValue = (value: T | ((val: T) => T)) => {
12 400">const valueToStore = value 400">instanceof Function ? 300">value(storedValue) : value;
13 300">setStoredValue(valueToStore);
14 window.localStorage.300">setItem(key, JSON.300">stringify(valueToStore));
15 };
16 
17 400">return [storedValue, setValue] 400">as 400">const;
18}

Resources

Related Technologies