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

Updating Context Values

Learn how to update shared Context values using React state and make the latest values available to consuming components.

1. What Does Updating Context Mean?

Context allows components to access shared information. When that information needs to change, React state can hold the current value and pass it to a Context Provider.

For example, a student portal may display a student's name and course in several components. When the student details change, the application can update its state and provide the new information through Context.

Remember: Context distributes a value. React state or another state-management mechanism manages changes to that value.

2. Understanding the Update Flow

User Clicks Button
↓
State Update Function
↓
Provider Gets New Value
↓
Consumer Components Update

A component calls a state setter, React renders the component with the updated state, and the Provider supplies the new value to its consumers.

3. Updating a Simple Theme Value

First, create a Context that stores the theme. The default value will be used only when no matching Provider exists.

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

const ThemeContext = createContext('light');

export default ThemeContext;

Now manage the theme using useState and provide it to a component.

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

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

    function changeTheme() {
        setTheme('dark');
    }

    return (
        <ThemeContext.Provider value={theme}>
            <ThemeDisplay />

            <button onClick={changeTheme}>
                Change Theme
            </button>
        </ThemeContext.Provider>
    );
}

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

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

    return (
        <h2>Current Theme: {theme}</h2>
    );
}

export default ThemeDisplay;

Expected Output

Initially: Current Theme: light

After clicking Change Theme: Current Theme: dark

The state setter changes the theme. The Provider receives the new theme value, and ThemeDisplay reads the updated value through useContext.

4. Updating an Object Stored in Context

Context can also distribute objects containing multiple related values. When updating an object in React state, create a new object instead of modifying the existing one.

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

const StudentContext = createContext(null);

export default StudentContext;
App.jsx
import { useState } from 'react';
import StudentContext from './StudentContext';
import StudentDetails from './StudentDetails';

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

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

    return (
        <StudentContext.Provider value={student}>
            <StudentDetails />

            <button onClick={updateStudent}>
                Update Student
            </button>
        </StudentContext.Provider>
    );
}

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

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

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

export default StudentDetails;

Expected Output

Before clicking:

Name: Samadhan

Course: React Development

After clicking Update Student:

Name: Samiksha

Course: Data Analytics

This example starts with an object in state and replaces it with a new object when the button is clicked. The Provider then supplies that new object to StudentDetails.

5. Updating One Property While Preserving Others

Sometimes only one property needs to change. Use the spread operator to preserve the other properties in the state object.

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

function updateCourse() {
    setStudent(previousStudent => ({
        ...previousStudent,
        course: 'Data Analytics'
    }));
}

Explanation

  • previousStudent represents the previous state value.
  • ... copies the existing properties into a new object.
  • course is overwritten with the new course name.
  • The name and city remain unchanged.

Expected Updated Data

Name: Samadhan

Course: Data Analytics

City: Pune

6. Updating Context for Multiple Components

Several components can consume the same Context. When the Provider value changes, all components reading that Context receive the latest value.

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

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

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

export default StudentName;
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;

Place both components inside the same Provider and use the state-update example from Section 4.

Expected Behavior

Before update: Student: Samadhan

Before update: Course: React Development

After update: Student: Samiksha

After update: Course: Data Analytics

7. Common Mistakes

Mistake 1: Mutating State Directly

Incorrect.jsx
student.name = 'Samiksha';

Do not directly modify an object held in React state. Instead, create a new object and pass it to the state setter.

Mistake 2: Forgetting to Pass State to the Provider

If the Provider continues receiving a fixed value, changing a separate state variable will not change the value supplied by that Provider. Pass the current state value to its value prop.

Mistake 3: Forgetting to Call the State Setter

Updating a normal variable does not trigger the same React state update behavior. Use the setter returned by useState.

Mistake 4: Expecting Context to Update Itself

Context does not automatically manage changing data. Use React state or another state-management mechanism to produce and update the value.

8. Best Practices

  • Keep changing values in React state.
  • Pass the current state value to the Provider.
  • Use state setters to update values.
  • Create new objects when updating object state.
  • Use the spread operator when preserving existing properties.
  • Keep Context values organized and easy to understand.
  • Use Context only when the value needs to be shared with descendant components.

9. Practice Tasks

Complete the following tasks.

  1. Create a ThemeContext and switch between light and dark themes using a button.
  2. Create a StudentContext with name and course properties.
  3. Update the student name when a button is clicked.
  4. Change only the course property while preserving the other object properties.
  5. Display the updated Context value in two different components.
  6. Explain why React state should not be mutated directly.
  7. Explain how a state update changes the value supplied by a Provider.

Summary

Updating Context values usually involves managing data with React state and passing the current state value to a Context Provider. When a state setter provides a new value, React renders the relevant component and updates consumers that read the changed Context. Use new objects for object-state updates and the spread operator to preserve properties that should not change. Context shares the value, while state manages its updates.