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

Context Provider

Learn how to provide shared values to React components using Context Provider and access those values with useContext.

1. What Is a Context Provider?

A Context Provider makes a value available to descendant components in a React component tree. Components can read that value using the useContext Hook without receiving it through props at every intermediate level.

For example, a training institute application may need to share a student's name and course with the dashboard, profile, and course components. A Provider can supply this information to all these components.

Remember: createContext creates the Context object, the Provider supplies its value, and useContext reads that value inside a component.

2. Syntax of Context Provider

Syntax.jsx
<MyContext.Provider value={someValue}>
    <ChildComponent />
</MyContext.Provider>

Explanation

  • MyContext is a Context object created using createContext.
  • .Provider makes the supplied Context value available to descendants.
  • value contains the data you want to share.
  • ChildComponent and its descendants can read the value using useContext.
The Provider only makes the value available within its descendant tree. Components outside that tree do not receive that Provider's value.

3. Create a Student Context

First, create a separate file to define the Context object. We will use it to share student information.

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

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

export default StudentContext;

Explanation

The StudentContext object is created using createContext. Its default value is an object with a name and course. A matching Provider can supply different values when the application runs.

4. Provide a Custom Value

Now create the parent App component and wrap the Student component inside StudentContext.Provider.

App.jsx
import StudentContext from './StudentContext';
import Student from './Student';

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

    return (
        <StudentContext.Provider value={student}>
            <Student />
        </StudentContext.Provider>
    );
}

export default App;

Explanation

  • The student object contains the name and course.
  • The Provider receives that object through its value prop.
  • The Student component is placed inside the Provider.
  • Student can now read the supplied object using useContext.

5. Read the Provided Value

The Student component reads the value from StudentContext using the useContext Hook.

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

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

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

export default Student;

Expected Output

Student Details

Name: Samadhan

Course: React Development

The values come from the Provider in App.jsx rather than from the default object in StudentContext.jsx.

6. Understanding the Component Tree

App
↓
StudentContext.Provider
value = student
↓
Student
↓
useContext(StudentContext)

React finds the closest matching Provider above Student and returns its current value. The Student component can use that value directly without receiving the student object through props.

7. Sharing Context with Multiple Components

A single Provider can make the same Context value available to several descendant components.

App.jsx
import StudentContext from './StudentContext';
import StudentProfile from './StudentProfile';
import StudentCourse from './StudentCourse';

function App() {
    const student = {
        name: 'Samiksha',
        course: 'Data Analytics'
    };

    return (
        <StudentContext.Provider value={student}>
            <StudentProfile />
            <StudentCourse />
        </StudentContext.Provider>
    );
}

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

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

    return <h2>Student: {student.name}</h2>;
}

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

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

    return <p>Course: {student.course}</p>;
}

export default StudentCourse;

Expected Output

Student: Samiksha

Course: Data Analytics

Both components read the same Context value. The intermediate component does not need to pass the student object through props.

8. What Happens When the Provider Value Changes?

When a Provider receives a different value, React updates components that read that Context. This makes Context useful for shared values that can change while the application runs.

For example, if a parent component uses useState to manage the current student's information and passes that state to the Provider, updating the state changes the value supplied by the Provider.

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

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

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

    return (
        <StudentContext.Provider value={student}>
            <Student />
            <button onClick={changeStudent}>
                Change Student
            </button>
        </StudentContext.Provider>
    );
}

export default App;

Use the Student.jsx component from Lesson 5 with this App.jsx example.

Expected Output

Before clicking:

Name: Samadhan

Course: React Development

After clicking Change Student:

Name: Samiksha

Course: Data Analytics

The button updates React state. The updated object is passed to the Provider, and the Student component receives the new Context value.

9. Common Mistakes

Mistake 1: Forgetting the value Prop

If you omit the value prop from a traditional Context.Provider, the provided value is undefined. Pass the intended value explicitly.

Mistake 2: Placing the Component Outside the Provider

A component outside the matching Provider does not receive that Provider's value. Place it inside the appropriate Provider tree.

Mistake 3: Using a Different Context Object

The Provider and useContext must reference the same Context object. Creating two separate Context objects does not make them interchangeable.

Mistake 4: Mutating the Existing Value

When managing Context data with state, create a new object when updating the value instead of mutating the existing object directly.

10. Best Practices

  • Create Context objects in a dedicated file when they are shared across multiple components.
  • Keep Providers as close as practical to the components that need the value.
  • Use meaningful names such as StudentContext or ThemeContext.
  • Provide a sensible default value that matches the intended data shape.
  • Keep state updates in React state rather than directly mutating Context objects.
  • Use props when only a nearby child needs a value and Context would add unnecessary complexity.

11. Practice Tasks

Complete these tasks to practise Context Provider.

  1. Create a ThemeContext and provide the value 'dark'.
  2. Create a LanguageContext and provide the value 'Marathi'.
  3. Create a StudentContext with student name and course properties.
  4. Display the same student name in two separate components using useContext.
  5. Use useState to change a Context value when a button is clicked.
  6. Explain why a component outside a Provider cannot read that Provider's supplied value.

Summary

A Context Provider supplies a value to descendant components through its value prop. Components can read that value with useContext, avoiding the need to forward props through every intermediate component. A Provider can share data with several components, and when its value changes, React updates components that consume the Context. Use React state to manage changing values and keep Context limited to information that genuinely needs to be shared.