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 useSelector and useDispatch

Learn how React components read Redux state using useSelector() and update state using useDispatch().

1. Introduction

React-Redux provides hooks that allow React components to work with the Redux store. Two of the most important hooks are useSelector() and useDispatch().

useSelector()

Reads the required data from the Redux store.

const count = useSelector(
    (state) => state.counter.value
);

useDispatch()

Provides the dispatch function used to send actions to the Redux store.

const dispatch = useDispatch();

dispatch(increment());
Remember: useSelector() reads selected state, while useDispatch() lets a component dispatch actions that can update that state.

2. Understanding useSelector()

useSelector() is a React-Redux hook that allows a component to select a value from the Redux store. When the selected result changes, React-Redux can trigger a re-render of the component.

Example Store Structure

{
    counter: {
        value: 10
    }
}

Reading the Counter Value

import { useSelector } from "react-redux";

function CounterValue() {
    const count = useSelector(
        (state) => state.counter.value
    );

    return (
        <h2>Counter Value: {count}</h2>
    );
}

export default CounterValue;

Explanation

useSelector() Reads a selected value from the store.
state Represents the current Redux state.
state.counter.value Accesses the counter value in this store structure.
count Stores the selected value in the component variable.
The state path must match your actual store configuration. If the reducer is registered under a different key, update the selector accordingly.

3. Selecting Data from Multiple Slices

A component can select data from different slices of the same Redux store. Consider an institute dashboard with student and course counts.

Example Store Structure

{
    students: {
        total: 25
    },
    courses: {
        total: 8
    }
}

Component Code

import { useSelector } from "react-redux";

function InstituteDashboard() {
    const studentCount = useSelector(
        (state) => state.students.total
    );

    const courseCount = useSelector(
        (state) => state.courses.total
    );

    return (
        <div>
            <h2>Students: {studentCount}</h2>
            <h2>Courses: {courseCount}</h2>
        </div>
    );
}

export default InstituteDashboard;

Expected Output

Total Students 25
Total Courses 8

4. Understanding useDispatch()

useDispatch() returns the Redux store's dispatch function. Components use this function to send actions to the store. The corresponding reducer processes the action and calculates the next state.

Example

import { useDispatch } from "react-redux";
import { increment } from "./counterSlice";

function IncrementButton() {
    const dispatch = useDispatch();

    return (
        <button onClick={() => dispatch(increment())}>
            Increment
        </button>
    );
}

export default IncrementButton;

How It Works

User Clicks Button
↓
dispatch(increment())
↓
Counter Reducer Runs
↓
Redux Store Holds Updated State
↓
UI Reflects Selected State

5. Create a Counter Slice

Before using useSelector() and useDispatch(), create a slice that defines the initial state and the actions that can update it.

File: counterSlice.js

import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
    name: "counter",

    initialState: {
        value: 0
    },

    reducers: {
        increment: (state) => {
            state.value += 1;
        },

        decrement: (state) => {
            state.value -= 1;
        },

        reset: (state) => {
            state.value = 0;
        }
    }
});

export const {
    increment,
    decrement,
    reset
} = counterSlice.actions;

export default counterSlice.reducer;

createSlice() automatically generates the increment, decrement, and reset action creators from the reducer definitions.

6. Configure the Redux Store

File: store.js

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

export const store = configureStore({
    reducer: {
        counter: counterReducer
    }
});

The counter reducer is registered under the counter key. Therefore, the counter value can be accessed using state.counter.value.

7. Complete Counter Component

Now combine useSelector() and useDispatch() to read and update the counter value.

File: Counter.jsx

import {
    useSelector,
    useDispatch
} from "react-redux";

import {
    increment,
    decrement,
    reset
} from "./counterSlice";

function Counter() {
    const count = useSelector(
        (state) => state.counter.value
    );

    const dispatch = useDispatch();

    return (
        <div>
            <h2>Counter: {count}</h2>

            <button onClick={() => dispatch(increment())}>
                Increment
            </button>

            <button onClick={() => dispatch(decrement())}>
                Decrement
            </button>

            <button onClick={() => dispatch(reset())}>
                Reset
            </button>
        </div>
    );
}

export default Counter;

8. Provide the Store to React

Wrap the application with Provider so that Counter can access the Redux store.

File: main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";

import { store } from "./store";
import Counter from "./Counter";

createRoot(document.getElementById("root")).render(
    <StrictMode>
        <Provider store={store}>
            <Counter />
        </Provider>
    </StrictMode>
);
Install Redux Toolkit and React-Redux if they are not already installed. This example assumes that the files are in the same directory; adjust import paths if your project uses folders.

9. Expected Counter Behavior

Counter: 0

Increment | Decrement | Reset

Initial state 0
Click Increment 1
Click Increment again 2
Click Decrement 1
Click Reset 0

These values show the expected behavior of the running React application. The preview above is illustrative; the actual buttons are implemented in Counter.jsx.

10. Common Mistakes

Incorrect State Path

Using state.value when the store actually contains state.counter.value causes the selector to read the wrong path.

Missing Provider

Components using React-Redux hooks must be rendered within a matching Provider that supplies the store.

Forgetting to Dispatch

Calling an action creator alone does not update the store. Dispatch the generated action using dispatch(actionCreator()).

Wrong Import Path

Verify the paths for counterSlice.js and store.js based on the folders in your project.

11. Practice Tasks

Task 1: Counter Application

Create a counter using useSelector() and useDispatch() with increment, decrement, and reset actions.

Task 2: Student Count

Create a students slice and display the total student count using useSelector().

Task 3: Add Student Button

Create an Add Student button that dispatches an action to increase the student count.

Task 4: Multiple Selectors

Create a dashboard that displays student and course totals from two different slices.

Summary

useSelector() reads selected values from the Redux store, while useDispatch() provides the function used to dispatch actions. When an action is dispatched, the corresponding reducer calculates the next state, and components subscribed to relevant state can update their UI. By combining createSlice(), configureStore(), Provider, useSelector(), and useDispatch(), React applications can manage shared state in a structured way. In the next lesson, we will learn how to handle asynchronous operations with Redux Toolkit.