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 API Best Practices

Learn how to use React Context API effectively, organize context code, avoid unnecessary re-renders, and build maintainable React applications with CIIT Training Institute.

1. Keep Context Focused

Create separate contexts for different types of data when they have different responsibilities. For example, authentication information and theme settings can use separate contexts.

import { createContext } from 'react';

export const ThemeContext = createContext('light');

export const AuthContext = createContext(null);

Best Practice: Avoid putting every piece of application data into one large context.

2. Use Meaningful Context Names

Give contexts, providers, and custom hooks clear names so that other developers can understand their purpose easily.

import { createContext, useContext } from 'react';

const ThemeContext = createContext(null);

export function useTheme() {
    return useContext(ThemeContext);
}

Here, ThemeContext stores theme-related data, and useTheme provides a convenient way to read it.

3. Place Providers at the Right Level

Place a provider around the components that need its value. Avoid wrapping the entire application when only a small section requires that context.

import { createContext, useState } from 'react';

const ThemeContext = createContext(null);

function ThemeProvider({ children }) {
    const [theme, setTheme] = useState('light');

    const value = { theme, setTheme };

    return (
        <ThemeContext.Provider value={value}>
            {children}
        </ThemeContext.Provider>
    );
}

Remember: Components can access a context value only when they are rendered within the corresponding provider's scope.

4. Avoid Unnecessary Re-renders

When a provider receives a different context value, components consuming that context may re-render. Creating a new object on every render can cause context consumers to update even when the underlying values have not changed.

Example using useMemo

import { createContext, useMemo, useState } from 'react';

const UserContext = createContext(null);

function UserProvider({ children }) {
    const [name, setName] = useState('Samadhan');

    const value = useMemo(() => ({
        name,
        setName
    }), [name]);

    return (
        <UserContext.Provider value={value}>
            {children}
        </UserContext.Provider>
    );
}

The memoized object keeps the same reference while name remains unchanged. When the name changes, React creates an updated value.

Important: Use memoization when it provides a meaningful performance benefit. It is not necessary for every context provider.

5. Use Custom Hooks for Context

A custom hook can centralize context access and provide a clear error when a component is rendered outside its provider.

import { createContext, useContext } from 'react';

const ThemeContext = createContext(undefined);

export function useTheme() {
    const context = useContext(ThemeContext);

    if (context === undefined) {
        throw new Error(
            'useTheme must be used within ThemeProvider'
        );
    }

    return context;
}

This approach makes context usage easier to maintain and helps developers identify missing providers during development.

6. Do Not Use Context for Every State

Context is useful for values needed by multiple components at different levels of the component tree. State that belongs to one component can usually remain local.

Local state example

import { useState } from 'react';

function SearchBox() {
    const [searchText, setSearchText] = useState('');

    return (
        <input
            type="text"
            value={searchText}
            onChange={(event) =>
                setSearchText(event.target.value)
            }
            placeholder="Search courses"
        />
    );
}

In this example, the search text is used only by SearchBox, so local state is a suitable choice.

7. Understand Context Limitations

  • Context is not a replacement for every state-management solution.
  • Consumers update when the provider's value changes.
  • Context does not automatically prevent unnecessary rendering.
  • Large applications may benefit from splitting contexts by responsibility.
  • Use a suitable state-management library when application requirements demand additional capabilities.

8. Recommended Project Structure

For a larger React application, keep context-related files organized so that providers and custom hooks are easy to locate.

src/
  contexts/
    ThemeContext.jsx
    AuthContext.jsx
  providers/
    ThemeProvider.jsx
    AuthProvider.jsx
  hooks/
    useTheme.js
    useAuth.js
  components/
    Header.jsx
    Dashboard.jsx
  App.jsx
  main.jsx

This is one possible structure. For a small project, a simpler structure may be sufficient.

Practice Tasks

  1. Create a ThemeContext with light and dark theme values.
  2. Build a ThemeProvider component using useState.
  3. Create a custom useTheme hook to read the context.
  4. Display the selected theme in a Header component.
  5. Add a button to switch between light and dark themes.
  6. Create a separate AuthContext for user information.
  7. Compare local state with Context API and decide which is appropriate for different examples.

Summary

React Context API helps share values across components without passing props through every intermediate component. Follow best practices by keeping contexts focused, naming them clearly, placing providers at appropriate levels, using custom hooks, and optimizing context values only when necessary. Keep local state local when possible, and choose the right state-management approach according to your application's needs.