Prerequisites & Fundamentals
Build a strong foundation in core web technologies essential for React development
Prerequisites & Fundamentals for React
Before diving into React development, mastering the foundational web technologies is essential for success. This lesson covers JavaScript fundamentals, ES6+ features, HTML/CSS basics, and development toolsβall reinforced with free flashcards and practice exercises to solidify your understanding. Whether you're starting from scratch or refreshing your skills, these prerequisites form the bedrock of effective React development.
Welcome to React Prerequisites! π»
React is a powerful JavaScript library for building user interfaces, but it's built on top of existing web technologies. Before you start creating components and managing state, you need a solid foundation in JavaScript, HTML, CSS, and modern development tools. This lesson will guide you through everything you need to know before writing your first React component.
π‘ Why Prerequisites Matter: Jumping into React without understanding JavaScript is like trying to write poetry without knowing the language. You'll be constantly confused about what's React and what's JavaScript!
Core Concepts in Detail
1. JavaScript Fundamentals π€
Variables and Data Types
JavaScript has three ways to declare variables:
let: Block-scoped, can be reassignedconst: Block-scoped, cannot be reassigned (use this by default!)var: Function-scoped, avoid in modern code
let count = 0; // Can change
const MAX = 100; // Cannot change
var oldStyle = 'no'; // Don't use this!
Primitive Types:
string:"hello",'world',`template`number:42,3.14,NaN,Infinityboolean:true,falseundefined: Variable declared but not assignednull: Intentional absence of valuesymbol: Unique identifier (rarely used)bigint: Large integers
Reference Types:
object:{key: value}array:[1, 2, 3]function:function() {}
Functions: The Heart of JavaScript
React heavily uses functions, so you need to master them:
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const greet = function(name) {
return `Hello, ${name}!`;
};
// Arrow function (most common in React!)
const greet = (name) => {
return `Hello, ${name}!`;
};
// Arrow function (concise)
const greet = name => `Hello, ${name}!`;
π‘ Arrow Function Tip: When you have a single expression, you can omit the curly braces and return keyword. This is extremely common in React!
Array Methods: Essential for React
React works with data transformations constantly. These array methods are crucial:
| Method | Purpose | Returns |
|---|---|---|
map() | Transform each element | New array |
filter() | Keep elements matching condition | New array |
find() | Get first matching element | Element or undefined |
reduce() | Combine elements into single value | Any type |
forEach() | Execute function for each element | undefined |
const numbers = [1, 2, 3, 4, 5];
// map: Double each number
const doubled = numbers.map(n => n * 2);
// Result: [2, 4, 6, 8, 10]
// filter: Keep only even numbers
const evens = numbers.filter(n => n % 2 === 0);
// Result: [2, 4]
// find: Get first number > 3
const found = numbers.find(n => n > 3);
// Result: 4
// reduce: Sum all numbers
const sum = numbers.reduce((total, n) => total + n, 0);
// Result: 15
2. ES6+ Modern JavaScript Features π
Destructuring: Extract Values Elegantly
Destructuring is everywhere in React code:
// Object destructuring
const user = { name: 'Alice', age: 30, city: 'NYC' };
const { name, age } = user;
console.log(name); // 'Alice'
// With renaming
const { name: username } = user;
console.log(username); // 'Alice'
// Array destructuring
const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
console.log(first); // 'red'
// In function parameters (very common in React!)
const UserCard = ({ name, age }) => {
return `${name} is ${age} years old`;
};
Spread Operator: Copy and Merge
The spread operator (...) is critical for working with React's immutable state:
// Copy array
const original = [1, 2, 3];
const copy = [...original];
// Merge arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
// Copy object
const user = { name: 'Bob', age: 25 };
const userCopy = { ...user };
// Merge objects (later properties override earlier ones)
const defaults = { theme: 'light', lang: 'en' };
const settings = { lang: 'es' };
const final = { ...defaults, ...settings };
// Result: { theme: 'light', lang: 'es' }
β οΈ Important: Spread creates a shallow copy only. Nested objects are still referenced!
Template Literals: String Interpolation
Use backticks for dynamic strings:
const name = 'World';
const greeting = `Hello, ${name}!`;
// Multi-line strings
const html = `
<div>
<h1>${name}</h1>
</div>
`;
// Expression evaluation
const price = 10;
const message = `Total: $${price * 1.2}`;
Promises and Async/Await: Handle Asynchronous Code
React often deals with API calls and async operations:
// Promise-based
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/await (cleaner!)
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
3. HTML & CSS Essentials π¨
HTML Structure
React components return HTML-like syntax (JSX). You need to know:
- Semantic elements:
<header>,<nav>,<main>,<article>,<section>,<footer> - Common elements:
<div>,<span>,<p>,<h1>-<h6>,<ul>,<ol>,<li> - Forms:
<form>,<input>,<textarea>,<select>,<button> - Attributes:
class,id,src,href,alt,type
<div class="container">
<h1 id="title">Welcome</h1>
<p>This is a paragraph.</p>
<img src="logo.png" alt="Logo" />
<a href="/about">About Us</a>
</div>
CSS Fundamentals
Styling React components requires CSS knowledge:
Selectors:
/* Element selector */
p { color: blue; }
/* Class selector */
.button { padding: 10px; }
/* ID selector */
#header { background: gray; }
/* Descendant selector */
.container p { margin: 20px; }
Box Model:
βββββββββββββββββββββββββββββββββββ
β MARGIN β
β βββββββββββββββββββββββββββββ β
β β BORDER β β
β β βββββββββββββββββββββββ β β
β β β PADDING β β β
β β β βββββββββββββββββ β β β
β β β β CONTENT β β β β
β β β β β β β β
β β β βββββββββββββββββ β β β
β β βββββββββββββββββββββββ β β
β βββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββ
Flexbox (crucial for React layouts):
.container {
display: flex;
justify-content: center; /* horizontal alignment */
align-items: center; /* vertical alignment */
flex-direction: row; /* or column */
gap: 10px; /* spacing between items */
}
4. Development Tools π οΈ
Node.js and npm
Node.js is a JavaScript runtime that lets you run JavaScript outside the browser. npm (Node Package Manager) comes with Node and manages project dependencies.
# Check if installed
node --version
npm --version
# Initialize a new project
npm init -y
# Install a package
npm install react
# Install as dev dependency
npm install --save-dev eslint
Package.json Structure
{
"name": "my-app",
"version": "1.0.0",
"dependencies": {
"react": "^18.2.0"
},
"devDependencies": {
"eslint": "^8.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build"
}
}
Module System: Import/Export
React apps are built with modules:
// math.js - Named exports
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// math.js - Default export
const calculator = { add, subtract };
export default calculator;
// app.js - Importing
import calculator from './math'; // Default import
import { add, subtract } from './math'; // Named imports
import * as math from './math'; // Import all
Practical Examples
Example 1: Array Transformation (Data Rendering Pattern)
This pattern is fundamental to Reactβtransforming data arrays into UI elements:
// Data from an API
const users = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
{ id: 3, name: 'Charlie', active: true }
];
// Filter active users and transform to display format
const activeUserNames = users
.filter(user => user.active)
.map(user => user.name.toUpperCase());
console.log(activeUserNames);
// Output: ['ALICE', 'CHARLIE']
Why this matters in React: You'll constantly convert data arrays into component arrays. Understanding map() and filter() is essential for rendering lists.
Example 2: Object Immutability (State Management Pattern)
React requires you to treat state as immutable. Here's how:
// β WRONG: Mutating original object
const user = { name: 'Alice', age: 30 };
user.age = 31; // Modifies original!
// β
RIGHT: Creating new object
const user = { name: 'Alice', age: 30 };
const updatedUser = { ...user, age: 31 };
// user is unchanged, updatedUser is new
// β WRONG: Mutating array
const items = [1, 2, 3];
items.push(4); // Modifies original!
// β
RIGHT: Creating new array
const items = [1, 2, 3];
const newItems = [...items, 4];
// items is unchanged, newItems is new
Why this matters in React: React's rendering system depends on detecting changes. Mutating objects directly breaks this system.
Example 3: Async Data Fetching (API Integration Pattern)
Fetching data is a core React task:
// Modern approach with async/await
const fetchUserData = async (userId) => {
try {
// Start loading state
console.log('Loading...');
// Fetch data
const response = await fetch(`https://api.example.com/users/${userId}`);
// Check if request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse JSON
const data = await response.json();
// Use data
console.log('Success:', data);
return data;
} catch (error) {
// Handle errors
console.error('Failed to fetch:', error.message);
return null;
}
};
// Usage
fetchUserData(123);
Why this matters in React: You'll use this pattern in useEffect hooks to load data when components mount.
Example 4: Destructuring in Function Parameters (Props Pattern)
This is how React components receive data:
// Without destructuring (harder to read)
const displayUser = (props) => {
return `${props.name} (${props.age}) - ${props.email}`;
};
// With destructuring (React style!)
const displayUser = ({ name, age, email }) => {
return `${name} (${age}) - ${email}`;
};
// With default values
const displayUser = ({ name, age = 18, email = 'N/A' }) => {
return `${name} (${age}) - ${email}`;
};
// Usage
const user = { name: 'Alice', age: 30, email: 'alice@example.com' };
console.log(displayUser(user));
// Output: "Alice (30) - alice@example.com"
Why this matters in React: React components receive props (properties) as objects. Destructuring in the function parameter makes code cleaner and more readable.
Common Mistakes β οΈ
1. Confusing == with ===
// β Loose equality (type coercion)
console.log(5 == '5'); // true (string converted to number)
console.log(0 == false); // true
console.log(null == undefined); // true
// β
Strict equality (no type coercion)
console.log(5 === '5'); // false
console.log(0 === false); // false
console.log(null === undefined); // false
Fix: Always use === and !== in React code.
2. Forgetting return in Arrow Functions
// β Missing return (returns undefined)
const double = (x) => {
x * 2; // No return!
};
// β
Explicit return
const double = (x) => {
return x * 2;
};
// β
Implicit return (concise)
const double = (x) => x * 2;
3. Mutating State Directly
// β Mutating original array
const items = [1, 2, 3];
items.push(4); // Modifies original
items[0] = 99; // Modifies original
items.sort(); // Modifies original
// β
Creating new arrays
const items = [1, 2, 3];
const added = [...items, 4];
const updated = items.map((item, i) => i === 0 ? 99 : item);
const sorted = [...items].sort();
4. Not Understanding Scope
// β var has function scope (confusing!)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3 (i is 3 when timeouts run)
// β
let has block scope
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2 (each i is separate)
5. Forgetting async with await
// β await without async
const getData = () => {
const data = await fetch('/api/data'); // ERROR!
};
// β
async function
const getData = async () => {
const data = await fetch('/api/data'); // Works!
};
6. Not Handling Async Errors
// β No error handling
const fetchData = async () => {
const response = await fetch('/api/data');
const data = await response.json();
// What if fetch fails? App crashes!
};
// β
With error handling
const fetchData = async () => {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('Failed');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
return null;
}
};
Key Concepts Summary π§
The "FADES" Memory Device
Remember these core prerequisites with FADES:
- Functions: Arrow functions, callbacks, array methods
- Async: Promises, async/await, API calls
- Destructuring: Objects, arrays, function parameters
- ES6+: Spread operator, template literals, modules
- State: Immutability, copying objects/arrays
Must-Know Before React Checklist β
- Can write arrow functions confidently
- Understand
map(),filter(), andfind()array methods - Know how to destructure objects and arrays
- Can use spread operator to copy/merge data
- Understand the difference between
const,let, andvar - Know how to use template literals for strings
- Can handle async operations with async/await
- Understand why immutability matters
- Know how to import/export modules
- Comfortable with basic HTML and CSS
Key Takeaways π―
JavaScript is the foundation: React is just JavaScript. The better you know JS, the easier React will be.
Array methods are crucial:
map(),filter(), andreduce()are used constantly for rendering lists and transforming data.Immutability is required: Never modify objects or arrays directly. Always create new ones using spread operator or array methods.
Async/await simplifies code: Use it for all API calls and asynchronous operations.
Destructuring makes code cleaner: Especially in function parametersβthis is the React way.
Arrow functions are standard: Learn their syntax variations, especially implicit returns.
ES6+ features are everywhere: Spread operator, template literals, and modules are used in every React app.
π Further Study
- MDN JavaScript Guide - Comprehensive JavaScript reference
- JavaScript.info - Modern JavaScript tutorial from basics to advanced
- You Don't Know JS - Deep dive into JavaScript mechanics
π Quick Reference Card
| Arrow Function | const fn = (x) => x * 2 |
| Destructure Object | const {name, age} = user |
| Destructure Array | const [first, second] = arr |
| Spread Array | const copy = [...original] |
| Spread Object | const updated = {...obj, key: val} |
| Template Literal | `Hello ${name}!` |
| Map Array | arr.map(x => x * 2) |
| Filter Array | arr.filter(x => x > 10) |
| Async Function | const fn = async () => await fetch(url) |
| Named Export | export const fn = () => {} |
| Default Export | export default Component |
| Import | import {fn} from './module' |