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

useRef Hook

Learn how to use the useRef Hook to store values between renders and access DOM elements without causing a re-render when the reference changes.

1. What Is the useRef Hook?

The useRef Hook is a built-in React Hook that returns a ref object containing a property called current. The value of this property can be changed without causing the component to re-render.

It is commonly used to access DOM elements, focus input fields, store timer IDs, and keep mutable values between renders.

Remember: Updating ref.current does not automatically update the UI. Use useState when a value needs to trigger a re-render.

2. Syntax of useRef

The basic syntax is:

import { useRef } from "react";

const myRef = useRef(initialValue);
  • useRef: The React Hook used to create a ref object.
  • initialValue: The initial value stored in the ref.
  • myRef.current: The property used to read or update the stored value.

3. How useRef Works

React creates a ref object that persists between renders. You can read or update its current value without asking React to render the component again.

Create Ref
→
Store Value
→
Update current
→
No Automatic Re-render
Important: A ref retains its object identity across renders. Changing its current value is not a replacement for React state.

4. Example: Accessing an Input Element

In this example, useRef stores a reference to an input element. When the button is clicked, the input field receives focus.

Example Code

import { useRef } from "react";

function App() {
    const inputRef = useRef(null);

    function focusInput() {
        inputRef.current.focus();
    }

    return (
        <div>
            <h2>Focus Input Example</h2>

            <input
                ref={inputRef}
                type="text"
                placeholder="Enter your name"
            />

            <button onClick={focusInput}>
                Focus Input
            </button>
        </div>
    );
}

export default App;

Expected Output

Focus Input Example

[ Enter your name ]

[ Focus Input ]

After clicking the button, the cursor moves to the input field.

Explanation: The inputRef object is attached to the input through the ref attribute. After React attaches the DOM element, inputRef.current refers to that element, allowing the code to call focus().

5. Example: Storing a Value with useRef

A ref can store a mutable value between renders. Updating that value does not trigger a re-render.

Example Code

import { useRef } from "react";

function App() {
    const clickCount = useRef(0);

    function handleClick() {
        clickCount.current += 1;

        console.log(
            "Button clicked:",
            clickCount.current,
            "times"
        );
    }

    return (
        <div>
            <h2>useRef Counter</h2>

            <button onClick={handleClick}>
                Click Me
            </button>
        </div>
    );
}

export default App;

Expected Output

useRef Counter

[ Click Me ]

After three clicks, the console shows:

Button clicked: 3 times

The count is stored in the ref and is not displayed automatically in the component.

Explanation: The clickCount.current value increases with each click. Because changing a ref does not trigger a re-render, the count is logged to the console instead of being automatically displayed in the UI.

6. Difference Between useRef and useState

  • useState: Stores state values and schedules a re-render when its setter updates the state.
  • useRef: Stores a mutable value that persists between renders without triggering a re-render when updated.
  • useState example: Displaying a counter value that changes on screen.
  • useRef example: Focusing an input field or storing a timer ID.
Remember: If changing a value must update the displayed UI, prefer useState. If you need to retain a value without causing a re-render, useRef may be appropriate.

7. Important Points About useRef

  • Import useRef from React.
  • Call Hooks at the top level of a component or custom Hook.
  • The ref object persists between renders.
  • Read or update the value through ref.current.
  • Updating a ref does not automatically re-render the component.
  • DOM refs are useful for focus, scrolling, and other imperative browser operations.

8. Practice Tasks

Complete the following exercises:

  1. Create an input field and focus it using useRef.
  2. Create a button that focuses an email input field.
  3. Store the number of button clicks in a ref and log the value to the console.
  4. Store a timer ID in a ref and clear the timer when required.
  5. Explain the difference between useRef and useState.

Summary

The useRef Hook creates a persistent reference object with a current property that can hold mutable values between renders. It is commonly used to access DOM elements, focus inputs, and store timer IDs or other values that do not need to trigger a UI update. Unlike useState, changing ref.current does not automatically cause a re-render. Understanding when to use refs and when to use state helps developers build effective React applications at CIIT Training Institute.