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

State Management Best Practices

CIIT Training Institute | Learn how to organize React state, use Redux Toolkit effectively, and build maintainable applications.

1. Introduction to State Management Best Practices

State management is an important part of building React applications. As an application grows, different components may need access to the same data. Without a clear strategy, state updates can become difficult to understand, test, and maintain.

Good state management means choosing the appropriate place for each piece of data, keeping updates predictable, avoiding unnecessary complexity, and organizing related application logic.

Important Principle

Do not put every piece of state into Redux. Use local component state for local UI behavior, and use shared state management when multiple parts of the application need coordinated access to the same data.

Choosing the Right State Management Approach

Application State
↓

Local State

useState()

Component-specific data

Shared State

Context or Redux

Data used across components

2. Keep State as Local as Possible

If a piece of state is needed by only one component, keep it inside that component. This makes the component easier to understand and avoids unnecessary global state.

Example: Local Input State

import { useState } from "react";

function StudentSearch() {
    const [search, setSearch] = useState("");

    return (
        <div>
            <input
                type="text"
                value={search}
                onChange={(event) =>
                    setSearch(event.target.value)
                }
                placeholder="Search students"
            />

            <p>Search: {search}</p>
        </div>
    );
}

export default StudentSearch;

The search value is used only by StudentSearch, so local state is sufficient. Redux is not required for this example.

Best Practice: Keep temporary UI state, such as input values, dropdown visibility, and modal visibility, local unless the application has a clear reason to share it.

3. Avoid Unnecessary Prop Drilling

Prop drilling occurs when data must pass through multiple intermediate components just to reach a deeply nested component. For simple component trees, props are perfectly appropriate. For deeply shared state, Context or Redux may be more suitable.

Example: Passing Props Through Components

function App() {
    const studentName = "Samadhan";

    return (
        <Dashboard studentName={studentName} />
    );
}

function Dashboard({ studentName }) {
    return (
        <StudentProfile studentName={studentName} />
    );
}

function StudentProfile({ studentName }) {
    return (
        <h2>Student: {studentName}</h2>
    );
}

This example is valid React. However, as the component tree becomes deeper, passing the same props through components that do not use them can make the code harder to maintain.

Use props when they provide a clear parent-to-child relationship. Consider Context or Redux when many unrelated components need access to shared application state.

4. Use Redux Toolkit for Shared State

Redux Toolkit is the recommended approach for writing Redux applications. It provides configureStore() and createSlice() to reduce boilerplate and organize state update logic.

Example: Counter Slice

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;

The slice keeps related reducer logic and action creators together. This is easier to maintain than scattering related Redux logic across many files.

5. Keep Reducers Predictable

Reducers should calculate the next state based on the current state and the action. They should not directly perform API requests, manipulate the DOM, or depend on unpredictable external side effects.

Example: Reducer with Redux Toolkit

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

    initialState: {
        value: 0
    },

    reducers: {
        incrementByAmount: (state, action) => {
            state.value += action.payload;
        }
    }
});

Dispatching the Action

dispatch(incrementByAmount(5));

If the current counter value is 10, the resulting value is 15. The reducer uses the action payload to calculate the next state.

Redux Toolkit uses Immer inside createSlice(), allowing mutation-like reducer syntax while maintaining immutable state updates.

6. Use useSelector() and useDispatch() Correctly

useSelector() reads selected values from the Redux store. useDispatch() provides the dispatch function for sending actions. Use them inside React function components or custom hooks.

Example

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

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

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

    const dispatch = useDispatch();

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

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

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

export default Counter;
The selector path must match the store configuration. For example, registering the counter reducer under the counter key makes state.counter.value the correct path.

7. Handle Loading, Success, and Error States

API requests can take time and may fail. A good application should clearly represent the request status instead of showing an empty screen or leaving users uncertain.

Example State Structure

const initialState = {
    data: [],
    loading: false,
    error: null
};

Render the Appropriate UI

if (loading) {
    return <p>Loading data...</p>;
}

if (error) {
    return <p>Error: {error}</p>;
}

return (
    <ul>
        {data.map((student) => (
            <li key={student.id}>
                {student.name}
            </li>
        ))}
    </ul>
);

Request State Flow

API Request Starts
↓
Loading State
↓

Success

Display the data

Error

Display an error message

8. Avoid Unnecessary State

Do not store values in state if they can be calculated from existing props or state. Duplicating the same information can cause values to become inconsistent.

Less Maintainable Approach

const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);
const [total, setTotal] = useState(200);

Here, total duplicates information that can be calculated from price and quantity.

Recommended Approach

const [price, setPrice] = useState(100);
const [quantity, setQuantity] = useState(2);

const total = price * quantity;

The total is calculated from the current values, so it does not need its own state variable.

9. Keep State Updates Immutable

In React, state should be updated according to the rules of the state management tool being used. With useState(), avoid mutating existing arrays or objects directly. With Redux Toolkit createSlice(), mutation-like syntax is supported because Immer creates the immutable updates.

React useState() Example

import { useState } from "react";

function StudentList() {
    const [students, setStudents] = useState([
        "Samadhan",
        "Samiksha"
    ]);

    function addStudent() {
        setStudents((previousStudents) => [
            ...previousStudents,
            "Prerna"
        ]);
    }

    return (
        <div>
            <button onClick={addStudent}>
                Add Student
            </button>

            {students.map((student) => (
                <p key={student}>{student}</p>
            ))}
        </div>
    );
}

export default StudentList;
Use the spread operator or other immutable update techniques for ordinary React state. Inside Redux Toolkit createSlice() reducers, Immer allows convenient mutation-like syntax.

10. Organize the Project Properly

A clear folder structure helps developers find related files, maintain features, and understand how state is managed.

Example Folder Structure

src/
|
|-- app/
|   |-- store.js
|
|-- features/
|   |-- counter/
|   |   |-- counterSlice.js
|   |   |-- Counter.jsx
|   |
|   |-- students/
|       |-- studentSlice.js
|       |-- StudentList.jsx
|
|-- App.jsx
|-- main.jsx

In this structure, store configuration is kept in the app folder, while each feature contains its related slice and components. Import paths should match the actual folder structure.

11. Common Mistakes to Avoid

Putting Everything in Redux

Not every input value, modal state, or temporary UI value needs to be stored globally.

Duplicating Derived Data

Calculate values from existing state whenever practical instead of maintaining unnecessary duplicate state.

Performing Side Effects in Reducers

Keep reducers focused on state updates. Use thunks or appropriate asynchronous tools for API requests.

Ignoring API Errors

Always consider loading, successful response, and failure states when building API-driven interfaces.

Using Incorrect Selector Paths

Make sure the path in useSelector() matches the reducers registered in configureStore().

12. Practice Tasks

Task 1: Local State

Create a search input using useState() and display the current search text.

Task 2: Redux Counter

Create a counter slice with increment, decrement, and reset actions, and connect it to a React component.

Task 3: Derived State

Create price and quantity state variables and calculate the total without storing it separately.

Task 4: API States

Fetch student data and display loading, success, and error states.

Task 5: Project Structure

Organize a React project into app, features, and component files with clear imports.

Summary

Effective state management begins by choosing the correct place for each piece of data. Local state is suitable for component-specific UI behavior, while Context or Redux can help manage shared state. Redux Toolkit provides organized slices and predictable state updates. Components can use useSelector() and useDispatch() to interact with Redux, while asynchronous operations should account for loading, success, and error states. Avoid unnecessary state, keep reducers predictable, and organize related files clearly. These practices help make React applications easier to maintain, debug, and extend.