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.
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.
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
Changing a value directly
const [name, setName] = useState("Avinash");
setName("Rahul");Try it: Change Name
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
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"
});
}Try it: Student Profile
Age: 25
Updating one property from an input
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.
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
This HTML page also changes its browser tab title to demonstrate the idea.
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.
| Form | Meaning 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
every render
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
The conceptual equivalent in React uses setInterval inside useEffect and clearInterval during cleanup.
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¤t=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
This demonstration is local, so the interactive page remains self-contained. The React source example above shows the real network call from the notes.
| Concept | Meaning |
|---|---|
useEffect | Run side-effect work after rendering. |
async | A function can perform asynchronous work. |
await | Wait for an asynchronous result inside that function. |
fetch() | Makes a network request. |
useState | Stores the result. |
9. useState vs useEffect
| useState | useEffect |
|---|---|
| Stores data | Performs side effects |
| Example: name | Example: API request |
| Example: count | Example: timer |
| State changes can cause a re-render | Runs after rendering |
setState() changes state | Effect synchronizes with the outside world |
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
How it works
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.
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.
| Purpose | Code | What it does |
|---|---|---|
| Focus | ref.current.focus() | Puts cursor/focus on an element |
| Remove focus | ref.current.blur() | Removes focus |
| Select text | ref.current.select() | Selects text in an input |
| Scroll | ref.current.scrollIntoView() | Scrolls to the element |
| Smooth scroll | ref.current.scrollIntoView({ behavior: "smooth" }) | Smoothly scrolls to the element |
| Play media | ref.current.play() | Starts playback |
| Pause media | ref.current.pause() | Pauses playback |
| Change position | ref.current.currentTime = 30 | Moves media to 30 seconds |
| Change volume | ref.current.volume = 0.5 | Sets volume to 50% |
| Mute | ref.current.muted = true | Mutes video/audio |
| Scroll to top | ref.current.scrollTop = 0 | Moves a scrollable element to the top |
12. Quick Reference
const [value, setValue] = useState(0)Current value + settersetValue("Avinash")Direct next valuesetValue(previous => previous + 1)Previous-state updater{ ...old, branch: newBranch }Preserve object propertiesuseEffect(() => { ... }, [])Effect after component appearsuseEffect(() => { ... }, [topic])Effect when topic changesuseRef(null)Persistent ref objectref.current.focus()Direct element controlOne-minute memory map
remember data
do extra work
hold / access
13. Quick Check
useState return?
useEffect in these notes?
[] generally mean in the source?
inputRef.current used for in the focus example?