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

Custom Hooks in React

Learn how to create Custom Hooks to reuse stateful logic across React components and organize your application code.

1. What Are Custom Hooks?

A Custom Hook is a JavaScript function that allows developers to reuse logic involving React Hooks across multiple functional components.

For example, if multiple components need to manage a counter, track a window size, or handle form input, that logic can be placed inside a Custom Hook and reused.

Remember: A Custom Hook name must start with use, such as useCounter or useWindowWidth.

2. Why Do We Use Custom Hooks?

Custom Hooks help separate reusable logic from component UI. Instead of writing the same state management logic repeatedly, developers can define it once and reuse it.

  • Reuse stateful logic across components.
  • Reduce repeated code.
  • Improve code readability and organization.
  • Keep components focused on displaying the UI.
  • Make shared logic easier to maintain.

3. How Custom Hooks Work

A component calls a Custom Hook just like it calls a built-in Hook. The Custom Hook can use built-in Hooks and return the values or functions the component needs.

Create Custom Hook
→
Use React Hooks
→
Return Values
→
Use in Component
Important: Each component calling a Custom Hook gets its own independent Hook state unless the logic explicitly uses a shared external store or context.

4. Example: Creating a Custom Counter Hook

In this example, we create a Custom Hook called useCounter. It manages a counter value and provides a function to increase it.

Example Code: useCounter.js

import { useState } from "react";

function useCounter() {
    const [count, setCount] = useState(0);

    function increaseCount() {
        setCount(previousCount =>
            previousCount + 1
        );
    }

    return {
        count,
        increaseCount
    };
}

export default useCounter;

Example Code: App.jsx

import useCounter from "./useCounter";

function App() {
    const { count, increaseCount } = useCounter();

    return (
        <div>
            <h2>Custom Hook Example</h2>

            <p>Count: {count}</p>

            <button onClick={increaseCount}>
                Increase Count
            </button>
        </div>
    );
}

export default App;

Expected Output

Custom Hook Example

Initially: Count: 0

After one click: Count: 1

After two clicks: Count: 2

Explanation: The useCounter Hook manages the count and returns the current value and the increase function. The App component uses those returned values to display and update the counter.

5. Reusing a Custom Hook in Multiple Components

The same Custom Hook can be called from different components. Each component maintains its own independent counter state.

Example Code: Counter.jsx

import useCounter from "./useCounter";

function Counter() {
    const { count, increaseCount } = useCounter();

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

            <button onClick={increaseCount}>
                Increase
            </button>
        </div>
    );
}

export default Counter;

Example Code: App.jsx

import Counter from "./Counter";

function App() {
    return (
        <div>
            <h2>Multiple Counters</h2>

            <Counter />
            <Counter />
        </div>
    );
}

export default App;

Expected Output

Multiple Counters

Counter: 0 [Increase]

Counter: 0 [Increase]

Clicking Increase in the first counter changes only the first counter's value. The second counter keeps its own value.

Explanation: Both Counter components reuse the same Custom Hook implementation. However, each call to useCounter() creates independent state for that component.

6. Example: Creating a Custom Input Hook

We can create a Custom Hook to manage the value of an input field and reuse the same logic in forms.

Example Code: useInput.js

import { useState } from "react";

function useInput(initialValue = "") {
    const [value, setValue] = useState(initialValue);

    function handleChange(event) {
        setValue(event.target.value);
    }

    return {
        value,
        onChange: handleChange
    };
}

export default useInput;

Example Code: App.jsx

import useInput from "./useInput";

function App() {
    const name = useInput("");
    const course = useInput("");

    return (
        <div>
            <h2>Student Registration</h2>

            <input
                placeholder="Enter name"
                {...name}
            />

            <br /><br />

            <input
                placeholder="Enter course"
                {...course}
            />

            <p>Name: {name.value}</p>
            <p>Course: {course.value}</p>
        </div>
    );
}

export default App;

Expected Output

Student Registration

[ Enter name ]

[ Enter course ]

After entering Samadhan and React:

Name: Samadhan
Course: React
Explanation: The useInput Hook manages an input value and its change handler. The spread syntax passes the returned value and onChange handler to each input field.

7. Rules for Creating Custom Hooks

  • Start the Custom Hook name with use.
  • Call built-in Hooks only at the top level of the Custom Hook.
  • Do not call Hooks inside loops, conditions, or nested functions.
  • Call Custom Hooks from React function components or other Custom Hooks.
  • Return the values or functions needed by the component using the Hook.
Remember: Custom Hooks share logic, not automatically shared state. Separate calls generally have separate state.

8. Practice Tasks

Complete the following exercises:

  1. Create a Custom Hook called useCounter with an increase function.
  2. Add decrease and reset functions to useCounter.
  3. Create a Custom Hook called useInput to manage text input values.
  4. Use the same Custom Hook in two separate components.
  5. Create a Custom Hook that tracks a boolean value and toggles it.
  6. Explain the difference between sharing logic and sharing state.

Summary

Custom Hooks are reusable JavaScript functions that allow developers to share logic involving React Hooks across functional components. Their names begin with use, and they can use built-in Hooks such as useState and useEffect. Custom Hooks help reduce repeated code, organize application logic, and make components easier to maintain. Each call generally maintains its own independent state, allowing the same logic to be reused in different components at CIIT Training Institute.