Learn the fundamentals of React and start building your first component-based applications with this comprehensive guide...
Table of Contents
- What is React?
- Prerequisites
- Setting Up Your Development Environment
- Your First React Component
- Understanding JSX
- Components and Props
- State and Lifecycle
- Handling Events
- Conditional Rendering
- Lists and Keys
- React Hooks
- Context API
- Forms and Controlled Components
- Refs and DOM Access
- Error Boundaries
- Performance Optimization
- Next Steps
What is React?
React is a popular JavaScript library for building user interfaces, particularly web applications. Developed by Facebook (now Meta), React allows developers to create reusable UI components that manage their own state. It's known for its component-based architecture, virtual DOM, and declarative programming style.
- Component-based architecture for reusable code
- Virtual DOM for efficient rendering
- One-way data flow for predictable updates
- Large ecosystem and community support
What is React?
React is a popular JavaScript library for building user interfaces, particularly web applications. Developed by Facebook (now Meta), React allows developers to create reusable UI components that manage their own state. It's known for its component-based architecture, virtual DOM, and declarative programming style.
- Component-based architecture for reusable code
- Virtual DOM for efficient rendering
- One-way data flow for predictable updates
- Large ecosystem and community support
Prerequisites
Before diving into React, you should have a basic understanding of:
- HTML & CSS: Fundamental markup and styling
- JavaScript: ES6+ features like arrow functions, destructuring, and modules
- Node.js & npm: For package management and running React apps
- Command Line: Basic terminal commands
Setting Up Your Development Environment
1. Install Node.js
Download and install Node.js from the official website (nodejs.org). This includes npm (Node Package Manager).
2. Create a New React App
Use Create React App to set up a new project:
npx create-react-app my-first-react-app
cd my-first-react-app
npm start
3. Project Structure
After creating your app, you'll see a structure like this:
my-first-react-app/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── App.js
│ ├── App.css
│ ├── index.js
│ └── index.css
├── package.json
└── README.md
Your First React Component
Let's create a simple "Hello World" component. Open src/App.js and replace its contents:
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Hello, React World!</h1>
<p>Welcome to your first React component.</p>
</header>
</div>
);
}
export default App;
Understanding JSX
JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It's not required but makes React code more readable.
// JSX
const element = <h1>Hello, world!</h1>;
// Equivalent JavaScript
const element = React.createElement('h1', null, 'Hello, world!');
Components and Props
Components are the building blocks of React applications. Props (properties) allow you to pass data from parent to child components.
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}
State and Lifecycle
State allows components to manage their own data that can change over time. Use the useState hook for functional components:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Handling Events
React events are similar to DOM events but use camelCase naming:
function ActionButton() {
function handleClick() {
alert('Button clicked!');
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
Conditional Rendering
You can conditionally render components using JavaScript operators:
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign up.</h1>;
}
// Or using ternary operator
function Greeting(props) {
return (
<h1>
{props.isLoggedIn ? 'Welcome back!' : 'Please sign up.'}
</h1>
);
}
Lists and Keys
When rendering lists, use the map() function and provide a unique key prop:
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
return (
<ul>{listItems}</ul>
);
}
React Hooks
Hooks are functions that let you "hook into" React state and lifecycle features from function components. The most important hooks for beginners are useState, useEffect, and useContext.
useEffect Hook
The useEffect hook lets you perform side effects in function components:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Context API
Context provides a way to pass data through the component tree without having to pass props down manually at every level. It's useful for global state like themes or user authentication.
// Create a context
const ThemeContext = React.createContext('light');
// Provider component
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
// Consumer component
function ThemedButton() {
return (
<ThemeContext.Consumer>
{theme => <button className={theme}>Button</button>}
</ThemeContext.Consumer>
);
}
Forms and Controlled Components
In React, form elements maintain their own state. A controlled component is one where React controls the form value.
function NameForm() {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value);
}
const handleSubmit = (event) => {
alert('A name was submitted: ' + value);
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={value} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
Refs and DOM Access
Refs provide a way to access DOM nodes or React elements created in the render method. They're useful when you need to imperatively modify a child or access a DOM element.
import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</div>
);
}
Error Boundaries
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log('Error caught by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
Performance Optimization
React provides several ways to optimize performance. The most common techniques include using React.memo, useMemo, and useCallback.
React.memo
const MyComponent = React.memo(function MyComponent(props) {
return <div>{props.value}</div>;
});
useMemo and useCallback
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
Next Steps
Now that you have the basics, here are some next steps to continue your React journey:
- Learn about React Router for navigation
- Explore state management with Redux or Context API
- Study React Hooks in depth
- Build a complete application
- Join the React community and contribute to open-source projects