Based on the uploaded 12-page React Hooks notes

React Hooks

Understand how function components work with state, effects, refs and reusable behavior — through small examples that are easy to run and explain in class.

useState useEffect useRef Updater function Dependency array API calls

1. What are Hooks?

Hooks are React functions that let function components use capabilities that historically belonged mainly to class components.

State

Store data that can change and update the UI.

Effects

Perform extra work after rendering, such as timers or API requests.

Refs

Persist a value between renders or access a DOM element through current.

Reusable behavior

Hooks also support context, reducers and memoization, and make custom Hooks easier to create.

Simple idea: Hooks let function components “remember, react, and reach outside the normal UI” without needing class syntax.

2. useState

useState returns an array containing the current state value and a setter function.

import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </>
  );
}

Try it: Counter

0
The initial value is used on the first render; later renders use the latest state.

Changing a value directly

const [name, setName] = useState("Avinash");

setName("Rahul");

Try it: Change Name

Avinash
Rule: Passing a direct value is suitable when the next value does not depend on the previous state.

3. Updater Function

The source recommends an updater function when the next state depends on the previous state, especially when several updates may be batched.

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

Why is it useful?

May be unreliable for “add 2”

setCount(count + 1);
setCount(count + 1);

Both updates may use the same count value from that render.

Functional updater

setCount(previousCount => previousCount + 1);
setCount(previousCount => previousCount + 1);

Each updater receives the latest previous value for the update.

Try it: Reserve Two

0

This page simulates the functional-updater result: two seats are added per click.

4. Objects and Arrays in State

For objects and arrays, the setter replaces the stored value. Preserve existing properties when updating an object with the spread operator.

const [student, setStudent] = useState({
  name: "Avinash",
  age: 25
});

function changeName() {
  setStudent({
    ...student,
    name: "Rahul"
  });
}
Old object
→
...student
→
Overwrite one property
→
New object

Try it: Student Profile

Name: Avinash
Age: 25

Updating one property from an input

Bob — CSE
function changeBranch(event) {
  setProfile(old => ({
    ...old,
    branch: event.target.value
  }));
}

5. useEffect and Side Effects

useEffect is used when React should perform extra work after rendering the screen / UI.

Browser title

Change the browser tab title.

Timer

Start a timer and clean it up when needed.

API request

Get data from an API after rendering.

External connection

Add a browser event listener or connect to an external service.

Remember the two questions: “What should I do?” and “When should I do it?”
useEffect(() => {
  // work to do

  return () => {
    // cleanup work
  };
}, [dependencies]);

Example: Changing the browser title

import { useEffect, useState } from 'react';

export default function App() {
  const [topic, setTopic] = useState('Components');

  useEffect(() => {
    document.title = `Study: ${topic}`;
  }, [topic]);

  return (
    <>
      <p>Current topic: {topic}</p>
      <button onClick={() => setTopic('Hooks')}>
        Change Topic
      </button>
    </>
  );
}

Try it: Topic & Browser Title

Current topic: Components

This HTML page also changes its browser tab title to demonstrate the idea.

Why useEffect here? The paragraph is part of React’s UI, but document.title = ... changes something outside that UI.

6. Dependency Array

The second part of useEffect is the dependency array. It tells React when the effect should run again.

FormMeaning in the source
useEffect(() => { ... })Runs after every render.
useEffect(() => { ... }, [])Runs after the component appears; cleanup runs on unmount.
useEffect(() => { ... }, [topic])Runs when topic changes.
[]
component starts
→
[topic]
topic changes
→
no array
every render
Classroom shortcut: Ask “When should this extra work happen?” Then choose the dependency form that matches that answer.

7. useEffect Timer

The source uses a timer to demonstrate an effect with setup and cleanup.

function Clock() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);

    return () => clearInterval(id);
  }, []);

  return <p>Seconds: {seconds}</p>;
}

Try it: Clock

0

The conceptual equivalent in React uses setInterval inside useEffect and clearInterval during cleanup.

Cleanup matters: When a component using the timer is removed, cleanup prevents the old interval from continuing to run.

8. useEffect with API Calls

The source demonstrates loading temperature data from an API with fetch(), storing the result with useState, and showing “Loading...” until the result arrives.

import { useEffect, useState } from 'react';

export default function App() {
  const [temperature, setTemperature] = useState(null);

  useEffect(() => {
    fetch(
      'https://api.open-meteo.com/v1/forecast?latitude=18.7762&longitude=84.095&current=rain,temperature_2m&forecast_days=1'
    )
      .then(response => response.json())
      .then(data => {
        setTemperature(data.current.temperature_2m);
      });
  }, []);

  return (
    <>
      <h1>Current Temperature</h1>
      <p>
        {temperature === null ? 'Loading...' : `${temperature} °C`}
      </p>
    </>
  );
}

API Call Concept Demo

Click “Simulate API call” to see the loading → result flow.

This demonstration is local, so the interactive page remains self-contained. The React source example above shows the real network call from the notes.

ConceptMeaning
useEffectRun side-effect work after rendering.
asyncA function can perform asynchronous work.
awaitWait for an asynchronous result inside that function.
fetch()Makes a network request.
useStateStores the result.

9. useState vs useEffect

useStateuseEffect
Stores dataPerforms side effects
Example: nameExample: API request
Example: countExample: timer
State changes can cause a re-renderRuns after rendering
setState() changes stateEffect synchronizes with the outside world
Easy distinction: useState answers “What data should this component remember?” useEffect answers “What extra work should happen after rendering?”

10. useRef

useRef stores a value that persists between renders without causing a re-render when that value changes. It can also directly access a DOM element through its current property.

import { useRef } from "react";

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

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

  return (
    <>
      <input ref={inputRef} placeholder="Enter your name" />
      <button onClick={focusInput}>
        Focus Input
      </button>
    </>
  );
}

Try it: Focus Input

Click a button to control the input focus.

How it works

useRef(null)
→
ref={inputRef}
→
inputRef.current
→
focus()

1

useRef(null) creates a ref object.

2

ref={inputRef} connects the ref to the input.

3

inputRef.current refers to the input element.

4

inputRef.current.focus() puts the cursor inside the input.

The notes emphasize that useRef is commonly used for direct HTML-element access without causing a re-render.

11. Video / Media Controls with useRef

The source uses a ref to call media methods such as play() and pause().

const videoRef = useRef(null);

function playVideo() {
  videoRef.current.play();
}

function pauseVideo() {
  videoRef.current.pause();
}
▶︎ 🎬

Media-control concept

In a React app, a ref can point to a <video> or <audio> element, then commands can be called through ref.current.

No media command selected.
PurposeCodeWhat it does
Focusref.current.focus()Puts cursor/focus on an element
Remove focusref.current.blur()Removes focus
Select textref.current.select()Selects text in an input
Scrollref.current.scrollIntoView()Scrolls to the element
Smooth scrollref.current.scrollIntoView({ behavior: "smooth" })Smoothly scrolls to the element
Play mediaref.current.play()Starts playback
Pause mediaref.current.pause()Pauses playback
Change positionref.current.currentTime = 30Moves media to 30 seconds
Change volumeref.current.volume = 0.5Sets volume to 50%
Muteref.current.muted = trueMutes video/audio
Scroll to topref.current.scrollTop = 0Moves a scrollable element to the top

12. Quick Reference

const [value, setValue] = useState(0)Current value + setter
setValue("Avinash")Direct next value
setValue(previous => previous + 1)Previous-state updater
{ ...old, branch: newBranch }Preserve object properties
useEffect(() => { ... }, [])Effect after component appears
useEffect(() => { ... }, [topic])Effect when topic changes
useRef(null)Persistent ref object
ref.current.focus()Direct element control
One-minute memory map
useState
remember data
→
useEffect
do extra work
→
useRef
hold / access

13. Quick Check

1. What does useState return?
2. When is an updater function especially useful?
3. What is the main purpose of useEffect in these notes?
4. What does an empty dependency array [] generally mean in the source?
5. What is inputRef.current used for in the focus example?