React.js Learning Path

From Basic to Advanced - Your Complete Guide

1. Introduction to React

React is a JavaScript library for building user interfaces, developed by Facebook. It's component-based, declarative, and uses a Virtual DOM for efficient updates.

Why React?

  • Component-based architecture for reusable UI
  • Virtual DOM for fast rendering
  • Large ecosystem and community
  • Used by major companies (Facebook, Netflix, Airbnb)

2. Setting Up React

Method 1: Create React App

npx create-react-app my-app cd my-app npm start

Method 2: CDN (for learning)

<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

3. JSX - JavaScript XML

JSX is a syntax extension that looks like HTML but is JavaScript.

const element = <h1>Hello, World!</h1>; // JSX with expressions const name = 'John'; const element = <h1>Hello, {name}!</h1>; // JSX attributes const element = <img src={user.avatarUrl} alt={user.name} />;
💡 Tip: JSX must return a single parent element. Use fragments (<>...</>) or <div> to wrap multiple elements.

4. Your First React Component

function Welcome(props) { return <h1>Hello, {props.name}</h1>; } // Using the component const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Welcome name="Sarah" />);

1. Functional Components

Modern React uses functional components with hooks.

function Greeting({ name, age }) { return ( <div> <h1>Hello, {name}!</h1> <p>You are {age} years old.</p> </div> ); }

2. Props (Properties)

Props are how you pass data from parent to child components.

function UserCard({ user }) { return ( <div className="card"> <img src={user.avatar} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> </div> ); } // Usage <UserCard user={{ name: 'John', email: 'john@example.com', avatar: '...' }} />
💡 Tip: Props are read-only. Never modify props inside a component.

3. State Management

State is data that changes over time in your component.

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

4. Event Handling

function Form() { const [name, setName] = useState(''); const handleSubmit = (e) => { e.preventDefault(); alert(`Hello, ${name}!`); }; return ( <form onSubmit={handleSubmit}> <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter name" /> <button type="submit">Submit</button> </form> ); }

5. Conditional Rendering

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

6. Lists and Keys

function TodoList({ todos }) { return ( <ul> {todos.map(todo => ( <li key={todo.id}> {todo.text} </li> ))} </ul> ); }
💡 Tip: Always use unique keys when rendering lists. This helps React identify which items have changed.

1. useState Hook

Manage state in functional components.

import { useState } from 'react'; function Example() { const [count, setCount] = useState(0); const [user, setUser] = useState({ name: '', age: 0 }); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ); }

2. useEffect Hook

Handle side effects like data fetching, subscriptions, or DOM manipulation.

import { useState, useEffect } from 'react'; function DataFetcher() { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { // Runs after component mounts fetch('https://api.example.com/data') .then(res => res.json()) .then(data => { setData(data); setLoading(false); }); // Cleanup function (optional) return () => { // Cleanup code here }; }, []); // Empty array = run once on mount if (loading) return <p>Loading...</p>; return <div>{/* Display data */}</div>; }
💡 Tip: The dependency array controls when useEffect runs. Empty [] = once, [value] = when value changes, no array = every render.

3. useContext Hook

Share data across components without prop drilling.

import { createContext, useContext } from 'react'; const ThemeContext = createContext(); function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); } function Toolbar() { const theme = useContext(ThemeContext); return <div className={theme}>Current theme: {theme}</div>; }

4. useRef Hook

Access DOM elements or persist values between renders.

import { useRef, useEffect } from 'react'; function TextInput() { const inputRef = useRef(null); useEffect(() => { // Focus input on mount inputRef.current.focus(); }, []); return <input ref={inputRef} type="text" />; }

5. useMemo Hook

Memoize expensive calculations.

import { useMemo, useState } from 'react'; function ExpensiveComponent({ numbers }) { const sum = useMemo(() => { // Only recalculates if numbers change return numbers.reduce((a, b) => a + b, 0); }, [numbers]); return <div>Sum: {sum}</div>; }

6. Custom Hooks

Create reusable logic by extracting it into custom hooks.

import { useState, useEffect } from 'react'; // Custom hook function useWindowWidth() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return width; } // Using the custom hook function MyComponent() { const width = useWindowWidth(); return <p>Window width: {width}px</p>; }

1. React Router

Add navigation and routing to your React app.

import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'; function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/users/:id" element={<User />} /> </Routes> </BrowserRouter> ); }

2. Performance Optimization

React.memo

const ExpensiveComponent = React.memo(function({ data }) { // Only re-renders if 'data' prop changes return <div>{data}</div>; });

useCallback

const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); // Only recreate if a or b changes

3. Error Boundaries

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, errorInfo); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }

4. State Management with Redux

// Store import { createStore } from 'redux'; const reducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; default: return state; } }; const store = createStore(reducer); // Component import { useSelector, useDispatch } from 'react-redux'; function Counter() { const count = useSelector(state => state.count); const dispatch = useDispatch(); return ( <button onClick={() => dispatch({ type: 'INCREMENT' })}> Count: {count} </button> ); }

5. API Integration Best Practices

import { useState, useEffect } from 'react'; function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchUsers = async () => { try { const response = await fetch('https://api.example.com/users'); if (!response.ok) throw new Error('Failed to fetch'); const data = await response.json(); setUsers(data); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchUsers(); }, []); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

Practice Projects

Build these projects to solidify your React knowledge:

Beginner Level:

  • Todo App: Add, delete, mark tasks complete
  • Calculator: Basic arithmetic operations
  • Weather App: Fetch weather data from API
  • Recipe Finder: Search and display recipes

Intermediate Level:

  • E-commerce Store: Product listing, cart, checkout
  • Movie Database: Search, filter, pagination
  • Social Media Dashboard: Posts, likes, comments
  • Task Management Board: Drag-and-drop Kanban board

Advanced Level:

  • Real-time Chat Application: WebSockets, user authentication
  • Project Management Tool: Complex state management, multiple views
  • Video Streaming Platform: Video player, playlists, recommendations
  • Analytics Dashboard: Charts, data visualization, real-time updates

Learning Resources

Official Documentation:

  • React Official Docs: react.dev
  • React Router: reactrouter.com
  • Redux: redux.js.org

Recommended Learning Path:

  1. Week 1-2: Basics - JSX, Components, Props
  2. Week 3-4: State Management, Hooks (useState, useEffect)
  3. Week 5-6: Advanced Hooks, Context API, Custom Hooks
  4. Week 7-8: Routing, Forms, API Integration
  5. Week 9-10: Performance Optimization, Testing
  6. Week 11-12: Advanced Patterns, Redux, Real Projects

Best Practices

  • Keep components small and focused
  • Use functional components with hooks
  • Avoid prop drilling - use Context API or state management
  • Implement proper error handling
  • Write clean, readable code with meaningful names
  • Use TypeScript for type safety (optional but recommended)
  • Follow React naming conventions (PascalCase for components)
  • Keep useState for local state, Context/Redux for global state
  • Optimize re-renders with React.memo and useMemo
  • Always clean up side effects in useEffect

Next Steps

After mastering React, explore these technologies:

  • Next.js: React framework for production with SSR
  • TypeScript: Add type safety to your React apps
  • React Native: Build mobile apps with React
  • Testing: Jest, React Testing Library
  • State Management: Redux Toolkit, Zustand, Recoil
  • UI Libraries: Material-UI, Chakra UI, Tailwind CSS