Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

Global State in React

1. Introduction to Global State

Global state is application data that can be accessed by multiple components. Instead of maintaining separate copies of the same information in different components, we can share state through a common provider or a state management solution.

For example, a shopping cart may be displayed in the navbar, product page and checkout page. Global state allows these components to access the same cart information.

Remember: Global state is useful when multiple components need the same data. Not every state value needs to be global.

2. Why Do We Need Global State?

  • Share common information across components.
  • Avoid passing the same props through many intermediate components.
  • Keep shared application data consistent.
  • Manage shopping cart, theme and user preferences.
  • Make shared state easier to maintain in larger applications.

3. Local State vs Global State

Local State Global State
Used within a particular component. Shared across multiple components.
Often managed using useState. Can use Context API or Redux Toolkit.
Example: form input value. Example: shared shopping cart.
Usually simpler to manage. Useful when shared state becomes more complex.

4. Global State Using React Context

React Context allows us to share values with components without passing props through every intermediate component. We create a context, provide its value and read it using useContext.

src/context/ThemeContext.jsx
import { createContext, useContext, useState } from "react";

const ThemeContext = createContext(null);

export function ThemeProvider({ children }) {
    const [theme, setTheme] = useState("light");

    function toggleTheme() {
        setTheme((currentTheme) =>
            currentTheme === "light" ? "dark" : "light"
        );
    }

    return (
        <ThemeContext.Provider
            value={{ theme, toggleTheme }}
        >
            {children}
        </ThemeContext.Provider>
    );
}

export function useTheme() {
    const context = useContext(ThemeContext);

    if (context === null) {
        throw new Error(
            "useTheme must be used within ThemeProvider"
        );
    }

    return context;
}
Explanation: The provider stores the theme and exposes both the current theme and the function used to change it. Components inside the provider can access this shared value.

5. Providing Global State to the Application

Wrap the application with ThemeProvider so its child components can access the shared theme.

src/main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { ThemeProvider } from "./context/ThemeContext";

createRoot(document.getElementById("root")).render(
    <StrictMode>
        <ThemeProvider>
            <App />
        </ThemeProvider>
    </StrictMode>
);

The provider is placed above the components that need access to the theme. Components outside this provider cannot use this context value.

6. Accessing Global State in a Component

The useTheme() custom Hook provides the current theme and the function to toggle it.

src/components/ThemeSwitcher.jsx
import { useTheme } from "../context/ThemeContext";

function ThemeSwitcher() {
    const { theme, toggleTheme } = useTheme();

    return (
        <div className={`theme-card ${theme}`}>
            <h2>Current Theme: {theme}</h2>

            <button onClick={toggleTheme}>
                Toggle Theme
            </button>
        </div>
    );
}

export default ThemeSwitcher;

7. Styling the Theme Component

src/App.css
.theme-card {
    padding: 24px;
    border-radius: 10px;
    border: 1px solid #d1d5db;
    transition: background-color 0.2s, color 0.2s;
}

.theme-card.light {
    background-color: #ffffff;
    color: #111827;
}

.theme-card.dark {
    background-color: #1f2937;
    color: #ffffff;
}

.theme-card button {
    padding: 10px 16px;
    border: none;
    border-radius: 6px;
    background-color: #2563eb;
    color: #ffffff;
    cursor: pointer;
}

8. Displaying the Component in App.jsx

src/App.jsx
import ThemeSwitcher from "./components/ThemeSwitcher";
import "./App.css";

function App() {
    return (
        <main>
            <h1>Global State Example</h1>
            <ThemeSwitcher />
        </main>
    );
}

export default App;

Expected Output

Current Theme: light

The component displays the current theme.

Toggle Theme

Clicking the button changes the theme state. The component re-renders to display the updated value.

9. Global State Flow

ThemeProvider
↓
Shared Theme State
↓
Navbar
ThemeSwitcher
Page Content

Multiple components can consume the same context value.

10. When Should You Use Global State?

  • When multiple components need the same information.
  • When application-wide preferences must remain consistent.
  • When passing props through many intermediate components becomes difficult.
  • When managing shared user interface state such as a theme or cart.
Best practice: Use local state for component-specific values. Use Context for suitable shared values, and consider Redux Toolkit when application state and update logic become more complex.

11. Practice Tasks

  1. Create a ThemeContext and a ThemeProvider.
  2. Display the theme in two different components.
  3. Add a button to switch between light and dark themes.
  4. Create a global language preference using Context.
  5. Build a shared cart count that can be displayed in the navbar and product page.
  6. Compare Context API with local component state.

Summary

Global state allows multiple React components to access shared application data. React Context can provide shared values without passing props through every intermediate component. By combining createContext, a provider, useContext and state Hooks, developers can manage shared information such as themes and user preferences.