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

Using Multiple Contexts

Learn how to create, provide, and read multiple Context values in the same React application.

1. What Are Multiple Contexts?

A React application can use more than one Context to share different types of information. For example, an application may use one Context for the selected theme and another Context for student information.

Each Context represents a separate value. Components can read one Context or several Contexts depending on the information they need.

Remember: Use separate Context objects when you want to organize different shared values, such as theme settings, user details, and language preferences.

2. Why Do We Need Multiple Contexts?

Consider a student portal that needs to share the selected theme and student details. These values have different purposes, so they can be stored in separate Context objects.

React Application
↓
ThemeContext
StudentContext
↓
Dashboard
Student Profile

The theme can be read from ThemeContext, while the student's name and course can be read from StudentContext.

3. Create ThemeContext

First, create a Context for the application's theme.

ThemeContext.jsx
import { createContext } from 'react';

const ThemeContext = createContext('light');

export default ThemeContext;

The default value is light. A Provider can supply another value, such as dark.

4. Create StudentContext

Next, create a separate Context for student information.

StudentContext.jsx
import { createContext } from 'react';

const StudentContext = createContext({
    name: 'Guest Student',
    course: 'Not Selected'
});

export default StudentContext;

StudentContext stores an object containing the student's name and course. This Context is independent of ThemeContext.

5. Provide Both Context Values

A component can nest multiple Providers so that its descendants can access both Context values.

App.jsx
import ThemeContext from './ThemeContext';
import StudentContext from './StudentContext';
import Dashboard from './Dashboard';

function App() {
    const student = {
        name: 'Samadhan',
        course: 'React Development'
    };

    return (
        <ThemeContext.Provider value="dark">
            <StudentContext.Provider value={student}>
                <Dashboard />
            </StudentContext.Provider>
        </ThemeContext.Provider>
    );
}

export default App;

Explanation

  • The outer Provider supplies the theme.
  • The inner Provider supplies the student object.
  • Dashboard is inside both Providers.
  • Dashboard and its descendants can read both Context values.
The order of the Providers matters when one Provider is rendered inside another Provider's component tree. In this example, Dashboard is inside both Context Providers.

6. Read Both Contexts in One Component

A component can call useContext more than once to read different Context objects.

Dashboard.jsx
import { useContext } from 'react';
import ThemeContext from './ThemeContext';
import StudentContext from './StudentContext';

function Dashboard() {
    const theme = useContext(ThemeContext);
    const student = useContext(StudentContext);

    return (
        <div>
            <h2>Student Dashboard</h2>
            <p>Theme: {theme}</p>
            <p>Student: {student.name}</p>
            <p>Course: {student.course}</p>
        </div>
    );
}

export default Dashboard;

Expected Output

Student Dashboard

Theme: dark

Student: Samadhan

Course: React Development

The component reads the theme and student details separately. No props are needed to forward either value through intermediate components.

7. Use Different Components for Different Contexts

A component does not have to read every available Context. It can consume only the information it needs.

ThemeDisplay.jsx
import { useContext } from 'react';
import ThemeContext from './ThemeContext';

function ThemeDisplay() {
    const theme = useContext(ThemeContext);

    return <p>Selected Theme: {theme}</p>;
}

export default ThemeDisplay;
StudentProfile.jsx
import { useContext } from 'react';
import StudentContext from './StudentContext';

function StudentProfile() {
    const student = useContext(StudentContext);

    return (
        <div>
            <h2>Student Profile</h2>
            <p>Name: {student.name}</p>
            <p>Course: {student.course}</p>
        </div>
    );
}

export default StudentProfile;

ThemeDisplay reads only ThemeContext. StudentProfile reads only StudentContext. Both can still be rendered inside the same Providers.

8. Updating Multiple Context Values

When Context values need to change, use React state and pass the current state to each Provider.

App.jsx
import { useState } from 'react';
import ThemeContext from './ThemeContext';
import StudentContext from './StudentContext';
import Dashboard from './Dashboard';

function App() {
    const [theme, setTheme] = useState('light');

    const [student, setStudent] = useState({
        name: 'Samadhan',
        course: 'React Development'
    });

    function changeTheme() {
        setTheme(previousTheme =>
            previousTheme === 'light' ? 'dark' : 'light'
        );
    }

    function changeStudent() {
        setStudent({
            name: 'Samiksha',
            course: 'Data Analytics'
        });
    }

    return (
        <ThemeContext.Provider value={theme}>
            <StudentContext.Provider value={student}>
                <Dashboard />

                <button onClick={changeTheme}>
                    Change Theme
                </button>

                <button onClick={changeStudent}>
                    Change Student
                </button>
            </StudentContext.Provider>
        </ThemeContext.Provider>
    );
}

export default App;

Use the Dashboard.jsx component from Section 6 with this example.

Expected Behavior

Initial values:

Theme: light

Student: Samadhan

Course: React Development

After Change Theme: Theme becomes dark.

After Change Student: Student becomes Samiksha and course becomes Data Analytics.

Each button updates its own state. React passes the updated values through their respective Providers.

9. Common Mistakes

Mistake 1: Using the Wrong Context

Pass ThemeContext to useContext when reading the theme, and StudentContext when reading student information.

Mistake 2: Forgetting a Provider

Without a matching Provider, a consumer receives that Context's default value.

Mistake 3: Using the Wrong Value Shape

If StudentContext provides an object, access properties such as student.name and student.course.

Mistake 4: Mutating State Directly

Use state setter functions and create new objects when updating state instead of changing existing objects directly.

Mistake 5: Adding Unnecessary Contexts

Not every value needs Context. For information used by only one nearby component, props may be simpler.

10. Best Practices

  • Use separate Context objects for logically different shared values.
  • Give each Context a meaningful name.
  • Place Providers around the components that need their values.
  • Read only the Context values needed by a component.
  • Use React state to manage changing Context values.
  • Keep each Context's data shape consistent.
  • Avoid introducing Context when ordinary props are sufficient.

11. Practice Tasks

Complete the following tasks.

  1. Create a ThemeContext with the default value 'light'.
  2. Create a StudentContext containing a name and course.
  3. Wrap a Dashboard component inside both Providers.
  4. Read both Context values inside Dashboard using useContext.
  5. Create a separate component that reads only ThemeContext.
  6. Use useState to change the theme and student details independently.
  7. Explain why multiple Context objects may be useful in a large application.

Summary

React applications can use multiple Context objects to share different types of information, such as theme settings and student details. Each Context has its own Provider and value, and components can read one or more Contexts with useContext. React state can be used to update these values independently. Keeping shared data organized into appropriate Contexts makes components easier to maintain and understand.