React.js Quick Reference

Concise guide to React.js with practical examples

React.js Quick Reference

React.js is a popular JavaScript library for building user interfaces, especially single-page applications.

Installation

# Create a new React app with Create React App
npx create-react-app my-app
cd my-app
npm start

# Or with Vite (faster)
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev

Basic Component

// Greeting.js
function Greeting() {
	return <h1>Hello, React!</h1>;
}

export default Greeting;

Props and State

import { useState } from "react";

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

export default Counter;

Handling Events

function ClickButton() {
	function handleClick() {
		alert("Button clicked!");
	}
	return <button onClick={handleClick}>Click me</button>;
}

Conditional Rendering

function UserGreeting({ isLoggedIn }) {
	return (
		<div>
			{isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}
		</div>
	);
}

Lists and Keys

function FruitList({ fruits }) {
	return (
		<ul>
			{fruits.map((fruit, idx) => (
				<li key={idx}>{fruit}</li>
			))}
		</ul>
	);
}

useEffect Hook

import { useEffect, useState } from "react";

function Timer() {
	const [seconds, setSeconds] = useState(0);
	useEffect(() => {
		const interval = setInterval(() => setSeconds(s => s + 1), 1000);
		return () => clearInterval(interval);
	}, []);
	return <div>Timer: {seconds}s</div>;
}

Fetching Data

import { useEffect, useState } from "react";

function UserList() {
	const [users, setUsers] = useState([]);
	useEffect(() => {
		fetch("https://jsonplaceholder.typicode.com/users")
			.then(res => res.json())
			.then(data => setUsers(data));
	}, []);
	return (
		<ul>
			{users.map(user => (
				<li key={user.id}>{user.name}</li>
			))}
		</ul>
	);
}

Component Composition

function Card({ title, children }) {
	return (
		<div className="card">
			<h2>{title}</h2>
			<div>{children}</div>
		</div>
	);
}

function App() {
	return (
		<Card title="About">
			<p>This is a reusable card component.</p>
		</Card>
	);
}

Best Practices

  1. Use functional components and hooks.
  2. Keep components small and focused.
  3. Use keys when rendering lists.
  4. Lift state up when needed.
  5. Keep side effects in useEffect.
  6. Use prop-types or TypeScript for type safety.

Resources