CoachnestCoachnest
For OrganizationsSign InGet Started
Back to course

Modern React & Next.js Masterclass

…
—
Contents
1

Why React? — The Modern UI Revolution

Reading8mFree
2

Setting Up Your Dev Environment

Video12m
3

React Foundations Quiz

Quiz10m

useState & useEffect Explained

Reading15m
5

Custom Hooks — Reusable Logic

Video18m
6

Context API & Global State

Reading14m
7

Next.js App Router In Depth

Video22m
8

Server Components vs Client Components

Reading16m
9

Final Assessment — React & Next.js

Quiz20m
←→navigate lessons
Chapter 2 of 3·Hooks & State
Lesson 4 of 9Reading15 min

useState & useEffect Explained

#useState & useEffect¶

The two most fundamental React hooks — master these and you can build almost anything.

useState¶

useState lets a component "remember" values between renders.

jsx
13 lines
1import { useState } from "react";
2
3function Counter() {
4  const [count, setCount] = useState(0);
5
6  return (
7    <div>
8      <p>Count: {count}</p>
9      <button onClick={() => setCount(count + 1)}>+</button>
10      <button onClick={() => setCount(count - 1)}>-</button>
11    </div>
12  );
13}

Rules of State¶

  • State updates are asynchronous — don't read state immediately after setting it.
  • State is immutable — always create a new value, never mutate directly.
  • Use the functional update form when new state depends on old state:
jsx
5 lines
1// ✅ Safe — uses functional update
2setCount(prev => prev + 1);
3
4// ❌ Risky — may use stale state
5setCount(count + 1);

useEffect¶

useEffect runs side effects after render — data fetching, subscriptions, DOM manipulation.

jsx
19 lines
1import { useState, useEffect } from "react";
2
3function UserProfile({ userId }) {
4  const [user, setUser] = useState(null);
5  const [loading, setLoading] = useState(true);
6
7  useEffect(() => {
8    setLoading(true);
9    fetch(`/api/users/${userId}`)
10      .then(res => res.json())
11      .then(data => {
12        setUser(data);
13        setLoading(false);
14      });
15  }, [userId]); // Re-runs when userId changes
16
17  if (loading) return <p>Loading…</p>;
18  return <h2>{user?.name}</h2>;
19}

The Dependency Array¶

UsageBehaviour
useEffect(fn)Runs after every render
useEffect(fn, [])Runs once (on mount)
useEffect(fn, [a, b])Runs when a or b changes

Cleanup¶

Always return a cleanup function when creating subscriptions or timers:

jsx
4 lines
1useEffect(() => {
2  const id = setInterval(() => setTick(t => t + 1), 1000);
3  return () => clearInterval(id); // Runs on unmount
4}, []);

Common mistake: Missing cleanup causes memory leaks in long-running apps.

Previous

React Foundations Quiz

Next

Custom Hooks — Reusable Logic

Use ← → arrow keys to navigate between lessons