Creating a Project
Installing Node.js and npm
- Download Node.js: Visit the Node.js official website and download the version compatible with your operating system.
- Install Node.js: Run the downloaded installer and follow the prompts to complete the installation.
- Verify Installation: Open a terminal and check the versions of Node.js and npm with the following commands:
node -v
npm -vCreating a New Project with Create React App
Install Create React App globally:
npm install -g create-react-appCreate a new project:
npx create-react-app my-app --template typescriptThe --template typescript flag is used for TypeScript projects. Omit it if TypeScript is not needed.
Navigate to the project directory and start the development server:
cd my-app
npm startProject Structure
src: Contains all source code.index.js: Application entry file.App.js: Main component file.components: Stores additional application components.services: May include API calls or data processing logic.styles: CSS or other styling files.public: Static resources and HTML files.index.html: Main HTML file.package.json: Lists project dependencies and scripts..gitignore: Specifies files to ignore in Git version control.
Component Pages
React components are divided into class components and functional components. Since React 18, functional components are preferred for their flexibility. Every function is a component, and components can be plugged in and out as needed.
Component Import and Export
export default function Button() {}
export function Button() {}
import Button from './Button.js';
import { Button } from './Button.js';JSX or TSX Syntax
- Wrap HTML sections in parentheses
(). - Use a parent tag to encapsulate multiple elements.
- Wrap variables, expressions, or function bodies in curly braces
{}.
export default function TodoList() {
return (
<>
<h1>Hedy Lamarr's Todos</h1>
<img
src="https://i.imgur.com/yXOvdOSs.jpg"
alt="Hedy Lamarr"
className="photo"
/>
<ul>
<li>Invent new traffic lights</li>
<li>Rehearse a movie scene</li>
<li>Improve spectrum technology</li>
</ul>
</>
);
}Component Property Passing
React components communicate via props, which can pass any JavaScript value, including objects, arrays, functions, or JSX, wrapped in {}.
import { getImageUrl } from './utils.js';
export default function Profile() {
return (
<Card>
<Avatar
size={100}
person={{
name: 'Katsuko Saruhashi',
imageId: 'YfeOqp2'
}}
/>
</Card>
);
}
// Reading props in a child component; in TypeScript, define an Interface or type for prop types
function Avatar({ person, size, isSepia, thickBorder }) {
return (
<img
className="avatar"
src={getImageUrl(person)}
alt={person.name}
width={size}
height={size}
isSepia={isSepia}
thickBorder={thickBorder}
/>
);
}
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}Component Rendering
Components often need to display different content based on conditions. In React, use JavaScript syntax like if, &&, and ?: operators to conditionally render JSX, wrapped in {}. A component must return something; return null to render nothing.
function Item({ name, isPacked }) {
return (
<>
<li className="item">
{name} {isPacked && '✔'}
</li>
<li className="item">
{isPacked ? (
<del>
{name + ' ✔'}
</del>
) : (
name
)}
</li>
</>
);
}
export default function PackingList() {
const listItems = people.map(person => (
<li key={person.id}>
<img
src={getImageUrl(person)}
alt={person.name}
/>
<p>
<b>{person.name}:</b>
{' ' + person.profession + ' '}
known for {person.accomplishment}
</p>
</li>
));
return (
<>
<article>
<h1>Scientists</h1>
<ul>{listItems}</ul>
</article>
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item
isPacked={true}
name="Space suit"
/>
<Item
isPacked={true}
name="Helmet with a golden leaf"
/>
<Item
isPacked={false}
name="Photo of Tam"
/>
</ul>
</section>
</>
);
}Handling Events
React allows adding event handlers to JSX. Event handlers are custom functions triggered by user interactions. Any JavaScript event (e.g., form, mouse, touch, keyboard, drag) can be added to component elements.
export default function App() {
return (
<Toolbar
onPlayMovie={() => alert('Playing!')}
onUploadImage={() => alert('Uploading!')}
/>
);
}
function Toolbar({ onPlayMovie, onUploadImage }) {
return (
<div>
<Button onClick={onPlayMovie}>
Play Movie
</Button>
<Button onClick={onUploadImage}>
Upload Image
</Button>
</div>
);
}
function Button({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
export default function Signup() {
return (
<form onSubmit={e => {
e.preventDefault();
alert('Submitting!');
}}>
<input />
<button>Send</button>
</form>
);
}e.stopPropagation(): Prevents triggering event handlers on parent elements.e.preventDefault(): Blocks default browser behavior for certain events.
Mouse Events
onClickonMouseDownonMouseUponMouseMoveonMouseEnteronMouseLeaveonContextMenu
Keyboard Events
onKeyDownonKeyPressonKeyUp
Form Events
onChangeonInputonSubmitonFocusonBlur
Touch Events
onTouchStartonTouchMoveonTouchEndonTouchCancel
Clipboard Events
onCopyonCutonPaste
Scroll Events
onScroll
Window Events
onResizeonScroll
Media Events
onPlayonPauseonLoadedDataonCanPlayonDurationChange
Animation Events
onAnimationStartonAnimationEndonAnimationIteration
Transition Events
onTransitionEnd
State Management
Using the useState() Hook
- State Variable: Retains data between renders.
- State Setter Function: Updates the variable and triggers a re-render.
// args: Defines the state variable
// setArgs: State setter function for updating the state
// default: Initial value (can be null, any JavaScript primitive, or a function)
const [args, setArgs] = useState(default);import { useState } from 'react';
import { sculptureList } from './data.js';
export default function Gallery() {
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);
function handleNextClick() {
setIndex(index + 1);
}
function handleMoreClick() {
setShowMore(!showMore);
}
let sculpture = sculptureList[index];
return (
<>
<button onClick={handleNextClick}>
Next
</button>
<h2>
<i>{sculpture.name} </i>
by {sculpture.artist}
</h2>
<h3>
({index + 1} of {sculptureList.length})
</h3>
<button onClick={handleMoreClick}>
{showMore ? 'Hide' : 'Show'} details
</button>
{showMore && <p>{sculpture.description}</p>}
<img
src={sculpture.url}
alt={sculpture.alt}
/>
</>
);
}import { useState } from 'react';
export default function Form() {
const [person, setPerson] = useState({
firstName: 'Barbara',
lastName: 'Hepworth',
email: 'bhepworth@sculpture.com'
});
function handleFirstNameChange(e) {
setPerson({
...person,
firstName: e.target.value
});
}
function handleLastNameChange(e) {
setPerson({
...person,
lastName: e.target.value
});
}
function handleEmailChange(e) {
setPerson({
...person,
email: e.target.value
});
}
return (
<>
<label>
First name:
<input
value={person.firstName}
onChange={handleFirstNameChange}
/>
</label>
<label>
Last name:
<input
value={person.lastName}
onChange={handleLastNameChange}
/>
</label>
<label>
Email:
<input
value={person.email}
onChange={handleEmailChange}
/>
</label>
<p>
{person.firstName}{' '}
{person.lastName}{' '}
({person.email})
</p>
</>
);
}Nested Object Structures
const [person, setPerson] = useState({
name: 'Niki de Saint Phalle',
artwork: {
title: 'Blue Nana',
city: 'Hamburg',
image: 'https://i.imgur.com/Sd1AgUOm.jpg',
}
});
setPerson({
...person, // Copy other fields
artwork: { // Replace the artwork
...person.artwork, // Keep existing fields
city: 'New Delhi' // Update city
}
});Updating Arrays in State
import { useState } from 'react';
let nextId = 0;
export default function List() {
const [name, setName] = useState('');
const [artists, setArtists] = useState([]);
return (
<>
<h1>Inspiring sculptors:</h1>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<button onClick={() => {
setArtists([
...artists,
{ id: nextId++, name: name }
]);
}}>Add</button>
<ul>
{artists.map(artist => (
<li key={artist.id}>{artist.name}</li>
))}
</ul>
</>
);
}Removing from an Array
import { useState } from 'react';
let initialArtists = [
{ id: 0, name: 'Marta Colvin Andrade' },
{ id: 1, name: 'Lamidi Olonade Fakeye'},
{ id: 2, name: 'Louise Nevelson'},
];
export default function List() {
const [artists, setArtists] = useState(initialArtists);
return (
<>
<h1>Inspiring sculptors:</h1>
<ul>
{artists.map(artist => (
<li key={artist.id}>
{artist.name}{' '}
<button onClick={() => {
setArtists(
artists.filter(a => a.id !== artist.id)
);
}}>
Delete
</button>
</li>
))}
</ul>
</>
);
}Sharing State Between Components
import { useState } from 'react';
export default function Accordion() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<>
<h2>Almaty, Kazakhstan</h2>
<Panel
title="About"
isActive={activeIndex === 0}
onShow={() => setActiveIndex(0)}
>
With a population of about 2 million, Almaty is Kazakhstan's largest city. From 1929 to 1997, it was its capital city.
</Panel>
<Panel
title="Etymology"
isActive={activeIndex === 1}
onShow={() => setActiveIndex(1)}
>
The name comes from <span lang="kk-KZ">алма</span>, the Kazakh word for "apple" and is often translated as "full of apples". In fact, the region surrounding Almaty is thought to be the ancestral home of the apple, and the wild <i lang="la">Malus sieversii</i> is considered a likely candidate for the ancestor of the modern domestic apple.
</Panel>
</>
);
}
function Panel({ title, children, isActive, onShow }) {
return (
<section className="panel">
<h3>{title}</h3>
{isActive ? (
<p>{children}</p>
) : (
<button onClick={onShow}>
Show
</button>
)}
</section>
);
}Using the useReducer() Hook
The useReducer hook consolidates all state update logic into a single reducer function outside the component.
Steps to use useReducer:
- Move from setting state to dispatching actions.
- Write a reducer function.
- Use the reducer in your component.
- Reducers must be pure: Like state update functions, reducers run during rendering. They must be pure—same inputs always produce the same output. Avoid side effects like requests or timeouts.
- Each action describes a single user interaction: For example, dispatching a
reset_formaction for a form reset is clearer than dispatching multipleset_fieldactions. Actions should be logged clearly for debugging.
import { useReducer } from 'react';
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
let nextId = 3;
const initialTasks = [
{ id: 0, text: 'Visit Kafka Museum', done: true },
{ id: 1, text: 'Watch a puppet show', done: false },
{ id: 2, text: 'Lennon Wall pic', done: false },
];
export default function TaskApp() {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
function handleAddTask(text) {
dispatch({
type: 'added',
id: nextId++,
text: text,
});
}
function handleChangeTask(task) {
dispatch({
type: 'changed',
task: task,
});
}
function handleDeleteTask(taskId) {
dispatch({
type: 'deleted',
id: taskId,
});
}
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added': {
return [
...tasks,
{
id: action.id,
text: action.text,
done: false,
},
];
}
case 'changed': {
return tasks.map(t => {
if (t.id === action.task.id) {
return action.task;
} else {
return t;
}
});
}
case 'deleted': {
return tasks.filter(t => t.id !== action.id);
}
default: {
throw Error('Unknown action: ' + action.type);
}
}
}
return (
<>
<h1>Prague itinerary</h1>
<AddTask onAddTask={handleAddTask} />
<TaskList
tasks={tasks}
onChangeTask={handleChangeTask}
onDeleteTask={handleDeleteTask}
/>
</>
);
}Component Communication
Using the useContext() Hook
Basic usage of useContext:
- Create a context object with
createContext. - Use
useContextto access the context value. - Wrap the root component with
<Context.Provider>.
import { useContext, createContext } from 'react';
export default function Section({ children }) {
const LevelContext = createContext(0);
const level = useContext(LevelContext);
return (
<section className="section">
<LevelContext.Provider value={level + 1}>
{children}
</LevelContext.Provider>
</section>
);
}useContext Summary:
- Context allows a component to provide information to its entire subtree.
- Passing Context:
- Create and export with
export const MyContext = createContext(defaultValue). - Read it with
useContext(MyContext)in any child component, regardless of depth. - Wrap children in
<MyContext.Provider value={...}>at the root component.
- Context passes through intermediate components.
- Context enables components to adapt to their environment.
- Before using context, try passing props or JSX as children.
useReducer and useContext Combined (For Shared State Management in Small Projects)
// App.js
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
import { TasksProvider } from './TasksContext.js';
export default function TaskApp() {
return (
<TasksProvider>
<h1>Day off in Kyoto</h1>
<AddTask />
<TaskList />
</TasksProvider>
);
}
// TasksContext.js
import { createContext, useContext, useReducer } from 'react';
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
{children}
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
export function useTasks() {
return useContext(TasksContext);
}
export function useTasksDispatch() {
return useContext(TasksDispatchContext);
}
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added': {
return [...tasks, {
id: action.id,
text: action.text,
done: false
}];
}
case 'changed': {
return tasks.map(t => {
if (t.id === action.task.id) {
return action.task;
} else {
return t;
}
});
}
case 'deleted': {
return tasks.filter(t => t.id !== action.id);
}
default: {
throw Error('Unknown action: ' + action.type);
}
}
}
const initialTasks = [
{ id: 0, text: 'Philosopher’s Path', done: true },
{ id: 1, text: 'Visit the temple', done: false },
{ id: 2, text: 'Drink matcha', done: false }
];
// AddTask.js
import { useState } from 'react';
import { useTasksDispatch } from './TasksContext.js';
export default function AddTask() {
const [text, setText] = useState('');
const dispatch = useTasksDispatch();
return (
<>
<input
placeholder="Add task"
value={text}
onChange={e => setText(e.target.value)}
/>
<button onClick={() => {
setText('');
dispatch({
type: 'added',
id: nextId++,
text: text,
});
}}>Add</button>
</>
);
}
let nextId = 3;
// TaskList.js
import { useState } from 'react';
import { useTasks, useTasksDispatch } from './TasksContext.js';
export default function TaskList() {
const tasks = useTasks();
return (
<ul>
{tasks.map(task => (
<li key={task.id}>
<Task task={task} />
</li>
))}
</ul>
);
}
function Task({ task }) {
const [isEditing, setIsEditing] = useState(false);
const dispatch = useTasksDispatch();
let taskContent;
if (isEditing) {
taskContent = (
<>
<input
value={task.text}
onChange={e => {
dispatch({
type: 'changed',
task: {
...task,
text: e.target.value
}
});
}} />
<button onClick={() => setIsEditing(false)}>
Save
</button>
</>
);
} else {
taskContent = (
<>
{task.text}
<button onClick={() => setIsEditing(true)}>
Edit
</button>
</>
);
}
return (
<label>
<input
type="checkbox"
checked={task.done}
onChange={e => {
dispatch({
type: 'changed',
task: {
...task,
done: e.target.checked
}
});
}}
/>
{taskContent}
<button onClick={() => {
dispatch({
type: 'deleted',
id: task.id
});
}}>
Delete
</button>
</label>
);
}Lifecycle
Mounting Phase
- The
constructormethod is executed first when creating a component instance. (A constructor is unnecessary if you don’t initialize state or bind methods.) - The
rendermethod is called next. - The
componentDidMountmethod is invoked immediately after the component is mounted (inserted into the DOM tree).
Updating Phase
- The
rendermethod is called immediately. - The
componentDidUpdatemethod is invoked right after the component updates.
Unmounting Phase
The componentWillUnmount method is called just before the component is unmounted and destroyed.
Directives
‘use client’
Meaning: Indicates that the component and its children execute on the client. Data fetching or computation logic defined within runs in the user’s browser, not on the server.
Use Cases:
- When components need access to the browser’s DOM or use React Hooks like
useStateoruseEffect. - When components handle user interactions, such as click events.
‘use server’
Meaning: Indicates that the component executes on the server. Rendering and related data fetching occur on the server, sending complete HTML to the client.
Use Cases:
- When components need server-side data fetching to reduce initial load time or avoid SSR issues.
- When rendering depends on server-side environments or data.
Fetch and Axios
Using the Fetch API
fetch is a browser-native API for making HTTP requests, returning a Promise that integrates well with asynchronous operations.
Example: Fetching and Displaying Data
import React, { useState, useEffect } from 'react';
function FetchExample() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => {
setError(error.message);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>Posts</h2>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default FetchExample;Explanation:
- useEffect: Executes side effects (e.g., network requests) on component mount.
- fetch: Initiates a GET request to the specified URL.
- response.json(): Parses the response body as JSON.
- Error Handling: Uses
try...catchor.catch()to handle errors.
Using Axios
axios is a popular HTTP client library with a simpler API and features like automatic JSON conversion and request cancellation.
Installing Axios
npm install axiosExample: Fetching and Displaying Data
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function AxiosExample() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
setData(response.data);
setLoading(false);
})
.catch((error) => {
setError(error.message);
setLoading(false);
});
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>Posts</h2>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default AxiosExample;Explanation:
- axios.get: Initiates a GET request to the specified URL.
- response.data: Directly accesses response data without additional parsing.
- Error Handling: Uses
.catch()to handle errors.
Advantages of Axios
- Automatic JSON Conversion: Automatically converts response bodies to JSON.
- Interceptors: Allows custom logic before requests or after responses.
- Request Cancellation: Supports canceling ongoing requests, useful for frequent page switches or form submissions.
- Concurrent Requests: Use
axios.allto handle multiple requests simultaneously.
Example: Using Interceptors and Request Cancellation
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function AxiosAdvancedExample() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const cancelSource = axios.CancelToken.source();
useEffect(() => {
// Request interceptor
axios.interceptors.request.use(
(config) => {
console.log('Request started:', config.url);
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor
axios.interceptors.response.use(
(response) => {
console.log('Response received:', response.config.url);
return response;
},
(error) => {
return Promise.reject(error);
}
);
// GET request
axios
.get('https://jsonplaceholder.typicode.com/posts', {
cancelToken: cancelSource.token,
})
.then((response) => {
setData(response.data);
setLoading(false);
})
.catch((thrown) => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
setError(thrown.message);
setLoading(false);
}
});
// Cleanup: Cancel request
return () => {
cancelSource.cancel('Component unmounted');
};
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>Posts</h2>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default AxiosAdvancedExample;



