CodeMasteryLab
Tutorials / React Complete Guide for Beginners

React Complete Guide for Beginners

A complete tutorial covering all React fundamentals including JSX, components, props, state management, hooks like useState and useEffect, event handling, and conditional rendering.

beginneršŸ“– 45 min readšŸ‘ 76 views

React Complete Guide for Beginners



Welcome to the complete React tutorial! React is a powerful JavaScript library for building user interfaces, created and maintained by Facebook (Meta). This guide will take you from zero to hero in React development.

Table of Contents



1. [What is React?](#what-is-react)
2. [Getting Started](#getting-started)
3. [Components and JSX](#components-and-jsx)
4. [Props: Passing Data](#props-passing-data)
5. [State Management](#state-management)
6. [Hooks Deep Dive](#hooks-deep-dive)
7. [Event Handling](#event-handling)
8. [Conditional Rendering](#conditional-rendering)
9. [Lists and Keys](#lists-and-keys)
10. [Real-World Example](#real-world-example)

---

What is React?



React is a JavaScript library for building user interfaces, particularly single-page applications where you need a fast, interactive user experience. React was created by Jordan Walke, a software engineer at Facebook, and was first deployed on Facebook's newsfeed in 2011.

Key Features of React



- Component-Based: Build encapsulated components that manage their own state
- Declarative: Design simple views for each state in your application
- Learn Once, Write Anywhere: Use React for web, mobile (React Native), and even VR
- Virtual DOM: Efficient rendering and updates
- Unidirectional Data Flow: Makes debugging easier and code more predictable

Why Learn React?



1. High Demand: React is one of the most in-demand skills in web development
2. Strong Ecosystem: Massive community, extensive libraries, and tools
3. Performance: Virtual DOM makes React applications fast
4. Career Growth: Used by Facebook, Netflix, Airbnb, Instagram, and thousands more

---

Getting Started



Prerequisites



Before learning React, you should have a basic understanding of:

- HTML & CSS
- JavaScript (ES6+ features like arrow functions, destructuring, spread operator)
- DOM manipulation basics

Setting Up Your Environment



#### Option 1: Create React App (Recommended for Beginners)

``bash

Create a new React app


npx create-react-app my-react-app

Navigate to the project


cd my-react-app

Start the development server


npm start
`

#### Option 2: Online Playground

Use online editors like:
- CodeSandbox (https://codesandbox.io)
- CodePen (https://codepen.io)
- StackBlitz (https://stackblitz.com)

Project Structure



After creating a React app, you'll see this structure:

`
my-react-app/
ā”œā”€ā”€ node_modules/
ā”œā”€ā”€ public/
│ ā”œā”€ā”€ index.html
│ └── favicon.ico
ā”œā”€ā”€ src/
│ ā”œā”€ā”€ App.js
│ ā”œā”€ā”€ App.css
│ ā”œā”€ā”€ index.js
│ └── index.css
ā”œā”€ā”€ package.json
└── README.md
`

---

Components and JSX



What are Components?



Components are the building blocks of React applications. They are reusable pieces of UI that can have their own logic and styling.

Functional Components



Modern React uses functional components with hooks:

`javascript
// Simple functional component
function Welcome() {
return

Hello, World!

;
}

// Or using arrow function
const Welcome = () => {
return

Hello, World!

;
};

export default Welcome;
`

JSX Syntax



JSX (JavaScript XML) allows you to write HTML-like code in JavaScript:

`javascript
function Profile() {
const user = {
name: "Sarah Johnson",
imageUrl: "https://i.imgur.com/yXOvdOSs.jpg",
imageSize: 90
};

return (

{user.name}


className="avatar"
src={user.imageUrl}
alt={'Photo of ' + user.name}
style={{
width: user.imageSize,
height: user.imageSize,
borderRadius: '50%'
}}
/>

);
}
`

JSX Rules



1. Single Parent Element: Must return one parent element

`javascript
// āœ… Correct
function MyComponent() {
return (

Title


Content



);
}

// āŒ Wrong
function MyComponent() {
return (

Title


Content


);
}

// āœ… Use Fragment
function MyComponent() {
return (
<>

Title


Content



);
}
`

2. Close All Tags: Self-closing tags must have
/>

`javascript
Description



`

3. className Instead of class: Use
className for CSS classes

`javascript
Content

`

4. Curly Braces for JavaScript: Use
{} to embed JavaScript

`javascript
const name = "React";
return

Welcome to {name}

;
`

---

Props: Passing Data



Props (properties) allow you to pass data from parent to child components.

Basic Props



`javascript
// Child component receiving props
function Welcome(props) {
return

Hello, {props.name}!

;
}

// Parent component passing props
function App() {
return (





);
}
`

Destructuring Props



`javascript
// Cleaner way using destructuring
function Welcome({ name, age, city }) {
return (

Hello, {name}!


Age: {age}


City: {city}



);
}

function App() {
return ;
}
`

Props with Objects



`javascript
function UserCard({ user }) {
return (

{user.name}

{user.name}


{user.email}


{user.role}



);
}

function App() {
const userData = {
name: "Sarah Johnson",
email: "sarah@example.com",
role: "Developer",
avatar: "https://i.imgur.com/avatar.jpg"
};

return ;
}
`

Props.children



Special prop that contains content between component tags:

`javascript
function Card({ children, title }) {
return (

{title}



{children}


);
}

function App() {
return (

This is the card content




);
}
`

---

State Management



State allows components to create and manage their own data. When state changes, the component re-renders.

useState Hook



The most fundamental React hook for managing state:

`javascript
import { useState } from 'react';

function Counter() {
// Declare state variable
const [count, setCount] = useState(0);

return (

You clicked {count} times






);
}
`

Multiple State Variables



`javascript
function UserProfile() {
const [name, setName] = useState('John');
const [age, setAge] = useState(25);
const [email, setEmail] = useState('john@example.com');

return (

{name}


Age: {age}


Email: {email}



);
}
`

State with Objects



`javascript
function UserForm() {
const [user, setUser] = useState({
firstName: '',
lastName: '',
email: ''
});

const handleChange = (e) => {
setUser({
...user,
[e.target.name]: e.target.value
});
};

return (

name="firstName"
value={user.firstName}
onChange={handleChange}
placeholder="First Name"
/>
name="lastName"
value={user.lastName}
onChange={handleChange}
placeholder="Last Name"
/>
name="email"
value={user.email}
onChange={handleChange}
placeholder="Email"
/>

);
}
`

State with Arrays



`javascript
function TodoList() {
const [todos, setTodos] = useState([]);
const [input, setInput] = useState('');

const addTodo = () => {
if (input.trim()) {
setTodos([...todos, { id: Date.now(), text: input }]);
setInput('');
}
};

const removeTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
};

return (

value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Add a todo"
/>


    {todos.map(todo => (

  • {todo.text}


  • ))}


);
}
`

---

Hooks Deep Dive



useEffect Hook



useEffect lets you perform side effects in function components (data fetching, subscriptions, manual DOM manipulation).

#### Basic useEffect

`javascript
import { useState, useEffect } from 'react';

function DocumentTitle() {
const [count, setCount] = useState(0);

useEffect(() => {
// This runs after every render
document.title =
You clicked ${count} times;
});

return (

);
}
`

#### useEffect with Dependencies

`javascript
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
// This runs only when userId changes
setLoading(true);
fetch(
https://api.example.com/users/${userId})
.then(response => response.json())
.then(data => {
setUser(data);
setLoading(false);
});
}, [userId]); // Dependency array

if (loading) return

Loading...

;

return (

{user.name}


{user.email}



);
}
`

#### useEffect Cleanup

`javascript
function Timer() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);

// Cleanup function
return () => {
clearInterval(interval);
};
}, []); // Empty array = run once on mount

return

Seconds: {seconds}

;
}
`

useEffect Dependency Patterns



`javascript
// Run once on mount
useEffect(() => {
console.log('Component mounted');
}, []);

// Run on every render
useEffect(() => {
console.log('Component rendered');
});

// Run when specific values change
useEffect(() => {
console.log('Count changed');
}, [count]);

// Run when any of multiple values change
useEffect(() => {
console.log('Count or name changed');
}, [count, name]);
`

---

Event Handling



React events are named using camelCase and pass functions as event handlers.

Button Click Events



`javascript
function ButtonExample() {
const handleClick = () => {
alert('Button clicked!');
};

// Inline function
const handleClickInline = () => {
console.log('Inline click');
};

return (





);
}
`

Form Events



`javascript
function LoginForm() {
const [formData, setFormData] = useState({
email: '',
password: ''
});

const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
console.log('Form submitted:', formData);
// Send data to server
};

const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};

return (

type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
type="password"
name="password"
value={formData.password}
onChange={handleChange}
placeholder="Password"
/>


);
}
`

Mouse Events



`javascript
function MouseExample() {
const [position, setPosition] = useState({ x: 0, y: 0 });

return (
onMouseMove={(e) => setPosition({ x: e.clientX, y: e.clientY })}
onMouseEnter={() => console.log('Mouse entered')}
onMouseLeave={() => console.log('Mouse left')}
style={{ height: '200px', border: '1px solid black' }}
>

X: {position.x}, Y: {position.y}



);
}
`

---

Conditional Rendering



If-Else with Variables



`javascript
function Greeting({ isLoggedIn }) {
let content;

if (isLoggedIn) {
content =

Welcome back!

;
} else {
content =

Please sign in

;
}

return
{content}
;
}
`

Ternary Operator



`javascript
function LoginStatus({ isLoggedIn }) {
return (

{isLoggedIn ? (

) : (

)}

);
}
`

Logical && Operator



`javascript
function Mailbox({ unreadMessages }) {
return (

Hello!


{unreadMessages.length > 0 && (

You have {unreadMessages.length} unread messages.


)}

);
}
`

Switch Statement Pattern



`javascript
function StatusBadge({ status }) {
const renderBadge = () => {
switch (status) {
case 'success':
return āœ“ Success;
case 'error':
return āœ— Error;
case 'warning':
return ⚠ Warning;
default:
return ℹ Info;
}
};

return
{renderBadge()}
;
}
`

---

Lists and Keys



Rendering Lists



`javascript
function TodoList() {
const todos = [
{ id: 1, text: 'Learn React', completed: false },
{ id: 2, text: 'Build a project', completed: false },
{ id: 3, text: 'Deploy to production', completed: true }
];

return (

    {todos.map(todo => (

  • {todo.text}
    {todo.completed && ' āœ“'}

  • ))}

);
}
`

Keys Explained



Keys help React identify which items have changed, are added, or removed:

`javascript
// āœ… Good - using unique ID
{items.map(item =>
  • {item.name}
  • )}

    // āš ļø OK - using index (only if list never changes)
    {items.map((item, index) =>
  • {item.name}
  • )}

    // āŒ Bad - no key
    {items.map(item =>
  • {item.name}
  • )}
    `

    Complex List Example



    `javascript
    function ProductList({ products }) {
    return (

    {products.map(product => (

    {product.name}

    {product.name}


    ${product.price}




    ))}

    );
    }
    `

    ---

    Real-World Example



    Let's build a complete Todo App combining everything we've learned:

    `javascript
    import { useState, useEffect } from 'react';

    function TodoApp() {
    const [todos, setTodos] = useState([]);
    const [input, setInput] = useState('');
    const [filter, setFilter] = useState('all'); // all, active, completed

    // Load todos from localStorage
    useEffect(() => {
    const saved = localStorage.getItem('todos');
    if (saved) {
    setTodos(JSON.parse(saved));
    }
    }, []);

    // Save todos to localStorage
    useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
    }, [todos]);

    const addTodo = (e) => {
    e.preventDefault();
    if (input.trim()) {
    setTodos([
    ...todos,
    {
    id: Date.now(),
    text: input,
    completed: false,
    createdAt: new Date().toISOString()
    }
    ]);
    setInput('');
    }
    };

    const toggleTodo = (id) => {
    setTodos(todos.map(todo =>
    todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ));
    };

    const deleteTodo = (id) => {
    setTodos(todos.filter(todo => todo.id !== id));
    };

    const filteredTodos = todos.filter(todo => {
    if (filter === 'active') return !todo.completed;
    if (filter === 'completed') return todo.completed;
    return true;
    });

    return (

    My Todo List



    {/* Add Todo Form */}

    type="text"
    value={input}
    onChange={(e) => setInput(e.target.value)}
    placeholder="What needs to be done?"
    />



    {/* Filter Buttons */}






    {/* Todo List */}

      {filteredTodos.map(todo => (

    • type="checkbox"
      checked={todo.completed}
      onChange={() => toggleTodo(todo.id)}
      />
      {todo.text}


    • ))}


    {/* Stats */}

    {filteredTodos.length} items


    {todos.filter(t => !t.completed).length} active




    );
    }

    export default TodoApp;
    `

    ---

    Next Steps



    Congratulations! You've learned the fundamentals of React. Here's what to learn next:

    Intermediate Topics


    - React Router: Navigation and routing
    - Context API: Advanced state management
    - Custom Hooks: Reusable logic
    - useReducer: Complex state logic
    - Performance Optimization: memo, useMemo, useCallback

    Advanced Topics


    - TypeScript with React: Type-safe React apps
    - Testing: Jest and React Testing Library
    - State Management: Redux, Zustand, Recoil
    - Server-Side Rendering: Next.js
    - React Native: Mobile app development

    Practice Projects


    1. Weather App with API
    2. E-commerce Product Page
    3. Social Media Dashboard
    4. Blog with Authentication
    5. Real-time Chat Application

    ---

    Common Mistakes to Avoid



    1. Mutating State Directly


    `javascript
    // āŒ Wrong
    state.count = state.count + 1;

    // āœ… Correct
    setState({ ...state, count: state.count + 1 });
    `

    2. Missing Keys in Lists


    `javascript
    // āŒ Wrong
    items.map(item =>
  • {item}
  • )

    // āœ… Correct
    items.map((item, id) =>
  • {item}
  • )
    `

    3. Forgetting to Prevent Default


    `javascript
    // āŒ Wrong - page reloads


    // āœ… Correct
    { e.preventDefault(); handleSubmit(); }}>
    `

    4. Comparing Objects in useEffect


    `javascript
    // āŒ Wrong - runs every render
    useEffect(() => {}, [objectProp]);

    // āœ… Correct - compare specific properties
    useEffect(() => {}, [objectProp.id, objectProp.name]);
    ``

    ---

    Best Practices



    1. Keep Components Small: One component, one responsibility
    2. Use Functional Components: Prefer hooks over class components
    3. Meaningful Names: Use descriptive names for components and functions
    4. DRY Principle: Don't repeat yourself - create reusable components
    5. PropTypes or TypeScript: Add type checking
    6. Folder Structure: Organize components logically
    7. Comments: Document complex logic
    8. Error Boundaries: Handle errors gracefully

    ---

    Resources



    - Official Docs: https://react.dev
    - React DevTools: Browser extension for debugging
    - Create React App: https://create-react-app.dev
    - Awesome React: Community-curated list of resources
    - React Patterns: Common design patterns

    ---

    Conclusion



    You now have a solid foundation in React! Remember:
    - Practice regularly: Build small projects
    - Read documentation: React docs are excellent
    - Join communities: Reddit, Discord, Stack Overflow
    - Stay updated: React evolves constantly
    - Contribute: Open source projects welcome beginners

    Happy coding! šŸš€