Part 07 / Stage 2
Custom hooks
Goal: Recognize duplicated
useState/useEffectlogic across components, extract it into a reusableuseXyzfunction, follow the rules that keep React able to track a component's hooks render after render, and build three small, genuinely reusable hooks (useToggle,useLocalStorage,useDebounce) - while telling apart what a custom hook actually shares (logic) from what it does not (state itself). Time: ~4 hours ยท Level: comfortable withuseStateanduseEffect(Part 6)
What you will learn
- The problem a custom hook solves: the same
useState+useEffectpair, typed twice (or more), across components that have nothing to do with each other except needing the same behavior - A custom hook is a plain function that calls other hooks - the
useprefix is a naming convention, not special syntax, and it is what lets React's own tooling (and the lint rule below) know a function is allowed to call hooks - The rules of hooks: call hooks only at the top level (never inside an
if, a loop, or after an early return), and only from a component or another custom hook - and the exact crash you get from breaking the first one useToggle,useLocalStorage,useDebounce- three small hooks, each verified by a real test, each reusing a pattern from Part 6 (cleanup, the dependency array) inside the hook itself instead of in every component that needs it- The one distinction this part cares about most: a custom hook shares logic - every call gets its own, independent state - it does not, by itself, share a value across components; sharing an actual value still needs that value to live in one place
- This part's running examples: a duplicated-then-extracted window-width tracker, two independent wishlist hearts, a broken product card that crashes, a persisted theme setting, and a debounced restaurant search
A note on how this part is organised: same convention as Parts 1-6 - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.
Topics in this part
Practice
Every exercise below is a custom hook and/or a component using it, each paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest - the same verified-output rule as every example in this course. Exercises involving timers use vi.useFakeTimers(), the same way examples/06_use_debounce.jsx does.
Exercise 1: A useCounter hook
Scenario: A Flipkart-style quantity stepper needs increment, decrement (never below 0), and reset - logic worth packaging once instead of re-typing in every product card.
What to do: Write useCounter(initialValue = 0) returning { count, increment, decrement, reset }, where decrement never takes count below 0. Write QuantityStepper() using it, with "+", "-", and "Reset" buttons.
Sample output (really run, starting at 0):
click "-" -> count stays 0 (never goes negative)
click "+" twice -> count: 2
click "Reset" -> count: 0
๐ก Hint: this is examples/03_use_toggle.jsx's useToggle shape, scaled up to three functions instead of one - increment/decrement both use an updater function (setCount(c => ...), Part 3's rule), and decrement clamps with Math.max(0, c - 1).
Exercise 2: Extract duplicated logic into useOnlineStatus
Scenario: A Swiggy-style order screen and a chat widget both want to know whether the browser currently reports itself online, each with their own copy of useState(navigator.onLine) plus online/offline window listeners.
What to do: Write OrderScreenBroken and ChatWidgetBroken with the duplicated logic described above (the same shape as examples/01_window_width_duplicated.jsx). Then extract useOnlineStatus() and rewrite both as OrderScreenFixed/ChatWidgetFixed, each calling the one hook.
Sample output (really run, dispatch a window "offline" event, then an "online" event):
before: both read "Status: online"
after dispatching "offline": both read "Status: offline"
after dispatching "online": both read "Status: online"
๐ก Hint: window.addEventListener("online", handler) / "offline" are the two events; navigator.onLine is the current value to seed useState with. This is examples/01_window_width_duplicated.jsx โ examples/02_use_window_width.jsx's exact move, renamed.
Exercise 3: Find and fix a rules-of-hooks violation
Scenario: A delivery-estimate card shows an extra "Express available" badge only for eligible pincodes, using its own state - a teammate wrote:
export function DeliveryEstimateBroken({ isExpressEligible }) {
if (isExpressEligible) {
const [badgeDismissed] = useState(false);
const [eta] = useState("2 days");
return <p>ETA: {eta} {badgeDismissed ? "" : "(Express available)"}</p>;
}
const [eta] = useState("2 days");
return <p>ETA: {eta}</p>;
}
Rendering it for an eligible pincode, then re-rendering the exact same instance for a non-eligible one, crashes.
What to do: Write both DeliveryEstimateBroken (the code above, unchanged - keep oxlint's react/rules-of-hooks warning visible and documented, the same way examples/04_rules_of_hooks_violation.jsx does) and DeliveryEstimateFixed, which calls both useState hooks unconditionally and branches only in the returned JSX.
Sample output (really run - mount with isExpressEligible={true}, then rerender with isExpressEligible={false}):
DeliveryEstimateBroken: throws "Rendered fewer hooks than expected..."
DeliveryEstimateFixed: renders "ETA: 2 days" with no error
๐ก Hint: examples/04_rules_of_hooks_violation.jsx's ConditionalProductCardBroken/Fixed pair is this exact shape - a hook that's only reachable in one branch, next to a hook every branch needs, renamed for a delivery estimate.
Exercise 4: A useSessionCart hook built on useLocalStorage
Scenario: A checkout flow wants a cart-item-count badge that survives a page refresh within the same browser tab, the same persistence examples/05_use_local_storage.jsx's useLocalStorage already provides for a theme setting.
What to do: Write useSessionCart(), a custom hook that calls useLocalStorage("cart-count", 0) internally and returns { count, addItem, clearCart } (addItem increments by 1, clearCart resets to 0) instead of exposing the raw setter. Write CartBadge() using it.
Sample output (really run, localStorage cleared before each test):
initial render -> "Cart: 0"
click "Add item" -> "Cart: 1", localStorage.getItem("cart-count") === "1"
unmount and remount -> "Cart: 1" (read back from localStorage)
click "Clear cart" -> "Cart: 0"
๐ก Hint: a custom hook can call another custom hook - useSessionCart never needs to touch localStorage directly, useLocalStorage already handles reading/writing/persisting; useSessionCart only adds the increment/reset vocabulary on top.
Exercise 5: A debounced restaurant search, end to end
Scenario: examples/06_use_debounce.jsx's RestaurantSearchBox only debounces the display text. A real search needs the debounced value to drive something else - counting how many times a (fake, for this course) "search" actually ran.
What to do: Write RestaurantSearchWithCount(): a text input backed by useDebounce(query, 400), plus a searchCount ref or state that increments inside a useEffect keyed on the debounced value (not the raw query) every time it changes to a non-empty value.
Sample output (vi.useFakeTimers(), really run - type "p", wait 100ms, type "pi", wait 100ms, type "piz", then wait the full 400ms):
immediately after typing "piz": "Searches run: 0" (still debouncing)
400ms later: "Searches run: 1" (only the final value triggered a search)
๐ก Hint: the effect that increments searchCount must depend on the debounced value returned by useDebounce, never on the raw query state - depending on query directly would run a "search" on every keystroke, defeating the entire point of debouncing.
Exercise 6: Sharing logic is not sharing state - fix a cart-count desync
Scenario: A layout has a cart icon in the header and a cart summary in a side panel. Both need to show the exact same item count. A teammate wrote both calling their own useLocalStorage("cart-count", 0) independently (the same hook as Exercise 4), assuming that reading the same localStorage key would keep them in sync.
What to do: Write HeaderCartIconBroken and CartSidePanelBroken, each with its own useLocalStorage("cart-count", 0) call, and prove that clicking "Add item" in one never updates the other (each hook call owns its own, independent useState - examples/03_use_toggle.jsx's lesson applies to any custom hook, not just useToggle). Then write CartLayoutFixed(), a shared parent that calls useLocalStorage exactly once and passes { count, addItem } down as props to a HeaderCartIconFixed and CartSidePanelFixed it renders - proving that lifting the hook call itself up to a shared parent (Part 3's lifting-state-up move, applied to a hook's return value) is what actually fixes it, not the hook alone.
Sample output (really run, click "Add item" inside the header icon):
Broken: header icon shows "Cart: 1", side panel still shows "Cart: 0" (independent state)
Fixed: header icon shows "Cart: 1", side panel ALSO shows "Cart: 1" (one shared value, passed down)
๐ก Hint: a custom hook packages reusable logic; it never packages a single shared value by itself. Two independent calls to the same hook are two independent pieces of state, full stop - sharing an actual value across components still needs the value to live in one place (a common parent here; useContext, Part 9, is the tool for when that parent is many levels away).
Show the solutions for Part 7 (12 files)
solutions/ex01_use_counter.jsx
// Exercise 1 solution.
//
// oxlint's react/only-export-components rule warns below because this
// file exports both a hook and the component that uses it - expected and
// left as a warning on purpose, the same as every hook file in this part.
import { useState } from "react";
export function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
function increment() {
setCount((current) => current + 1);
}
function decrement() {
setCount((current) => Math.max(0, current - 1));
}
function reset() {
setCount(initialValue);
}
return { count, increment, decrement, reset };
}
export function QuantityStepper() {
const { count, increment, decrement, reset } = useCounter(0);
return (
<div>
<p>Quantity: {count}</p>
<button onClick={decrement}>-</button>
<button onClick={increment}>+</button>
<button onClick={reset}>Reset</button>
</div>
);
}
solutions/ex01_use_counter.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { QuantityStepper } from "./ex01_use_counter.jsx";
describe("QuantityStepper uses useCounter for increment/decrement/reset", () => {
it("really never goes below 0, and resets back to the initial value", async () => {
const user = userEvent.setup();
render(<QuantityStepper />);
expect(screen.getByText("Quantity: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "-" }));
expect(screen.getByText("Quantity: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "+" }));
await user.click(screen.getByRole("button", { name: "+" }));
expect(screen.getByText("Quantity: 2")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Reset" }));
expect(screen.getByText("Quantity: 0")).toBeInTheDocument();
});
});
solutions/ex02_use_online_status.jsx
// Exercise 2 solution: the same duplicated-logic-then-extraction move as
// examples/01_window_width_duplicated.jsx -> examples/02_use_window_width.jsx,
// renamed for online/offline status.
//
// oxlint's react/only-export-components rule warns below because this
// file exports both a hook and the components that use it - expected and
// left as a warning on purpose, the same as every hook file in this part.
import { useEffect, useState } from "react";
export function OrderScreenBroken() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return <p>Order screen status: {isOnline ? "online" : "offline"}</p>;
}
export function ChatWidgetBroken() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return <p>Chat widget status: {isOnline ? "online" : "offline"}</p>;
}
export function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return isOnline;
}
export function OrderScreenFixed() {
const isOnline = useOnlineStatus();
return <p>Order screen status: {isOnline ? "online" : "offline"}</p>;
}
export function ChatWidgetFixed() {
const isOnline = useOnlineStatus();
return <p>Chat widget status: {isOnline ? "online" : "offline"}</p>;
}
solutions/ex02_use_online_status.test.jsx
import { act, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it } from "vitest";
import { ChatWidgetBroken, ChatWidgetFixed, OrderScreenBroken, OrderScreenFixed } from "./ex02_use_online_status.jsx";
beforeEach(() => {
Object.defineProperty(window.navigator, "onLine", { value: true, writable: true, configurable: true });
});
function goOffline() {
Object.defineProperty(window.navigator, "onLine", { value: false, writable: true, configurable: true });
act(() => window.dispatchEvent(new Event("offline")));
}
function goOnline() {
Object.defineProperty(window.navigator, "onLine", { value: true, writable: true, configurable: true });
act(() => window.dispatchEvent(new Event("online")));
}
describe("OrderScreenBroken and ChatWidgetBroken each duplicate the online/offline logic", () => {
it("both still react to the same browser events, despite the duplication", () => {
render(
<div>
<OrderScreenBroken />
<ChatWidgetBroken />
</div>,
);
expect(screen.getByText("Order screen status: online")).toBeInTheDocument();
expect(screen.getByText("Chat widget status: online")).toBeInTheDocument();
goOffline();
expect(screen.getByText("Order screen status: offline")).toBeInTheDocument();
expect(screen.getByText("Chat widget status: offline")).toBeInTheDocument();
});
});
describe("OrderScreenFixed and ChatWidgetFixed both call the one useOnlineStatus hook", () => {
it("still react correctly, with the logic written exactly once", () => {
render(
<div>
<OrderScreenFixed />
<ChatWidgetFixed />
</div>,
);
goOffline();
expect(screen.getByText("Order screen status: offline")).toBeInTheDocument();
expect(screen.getByText("Chat widget status: offline")).toBeInTheDocument();
goOnline();
expect(screen.getByText("Order screen status: online")).toBeInTheDocument();
expect(screen.getByText("Chat widget status: online")).toBeInTheDocument();
});
});
solutions/ex03_delivery_estimate.jsx
// Exercise 3 solution: same bug and fix as examples/04_rules_of_hooks_violation.jsx,
// renamed for a delivery-estimate card.
import { useState } from "react";
export function DeliveryEstimateBroken({ isExpressEligible }) {
if (isExpressEligible) {
// This line breaks the rules of hooks on purpose, to show the exact
// crash it prevents (see the paired test) - documented and left
// visible rather than silenced, the same as examples/04's violation.
// oxlint-disable-next-line react/rules-of-hooks
const [badgeDismissed] = useState(false);
// oxlint-disable-next-line react/rules-of-hooks
const [eta] = useState("2 days");
return (
<p>
ETA: {eta} {badgeDismissed ? "" : "(Express available)"}
</p>
);
}
// oxlint-disable-next-line react/rules-of-hooks
const [eta] = useState("2 days");
return <p>ETA: {eta}</p>;
}
export function DeliveryEstimateFixed({ isExpressEligible }) {
const [badgeDismissed] = useState(false);
const [eta] = useState("2 days");
return isExpressEligible ? (
<p>
ETA: {eta} {badgeDismissed ? "" : "(Express available)"}
</p>
) : (
<p>ETA: {eta}</p>
);
}
solutions/ex03_delivery_estimate.test.jsx
import { render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DeliveryEstimateBroken, DeliveryEstimateFixed } from "./ex03_delivery_estimate.jsx";
describe("DeliveryEstimateBroken crashes once its hook order shifts", () => {
beforeEach(() => {
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
console.error.mockRestore();
});
it("really throws on a rerender that flips isExpressEligible", () => {
const { rerender } = render(<DeliveryEstimateBroken isExpressEligible={true} />);
expect(screen.getByText(/ETA: 2 days/)).toBeInTheDocument();
expect(() => rerender(<DeliveryEstimateBroken isExpressEligible={false} />)).toThrow(
/Rendered fewer hooks than expected/,
);
});
});
describe("DeliveryEstimateFixed calls both hooks unconditionally", () => {
it("really never throws, and renders the right badge either way", () => {
const { rerender } = render(<DeliveryEstimateFixed isExpressEligible={true} />);
expect(screen.getByText("ETA: 2 days (Express available)")).toBeInTheDocument();
expect(() => rerender(<DeliveryEstimateFixed isExpressEligible={false} />)).not.toThrow();
expect(screen.getByText("ETA: 2 days")).toBeInTheDocument();
});
});
solutions/ex04_use_session_cart.jsx
// Exercise 4 solution: a custom hook built on top of another custom hook -
// useSessionCart never touches localStorage itself, it reuses
// useLocalStorage for that and only adds the increment/reset vocabulary.
//
// oxlint's react/only-export-components rule warns below because this
// file exports both hooks and the component that uses them - expected
// and left as a warning on purpose, the same as every hook file in this part.
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = window.localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
export function useSessionCart() {
const [count, setCount] = useLocalStorage("cart-count", 0);
function addItem() {
setCount((current) => current + 1);
}
function clearCart() {
setCount(0);
}
return { count, addItem, clearCart };
}
export function CartBadge() {
const { count, addItem, clearCart } = useSessionCart();
return (
<div>
<p>Cart: {count}</p>
<button onClick={addItem}>Add item</button>
<button onClick={clearCart}>Clear cart</button>
</div>
);
}
solutions/ex04_use_session_cart.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it } from "vitest";
import { CartBadge } from "./ex04_use_session_cart.jsx";
beforeEach(() => {
window.localStorage.clear();
});
describe("CartBadge persists its count via useSessionCart -> useLocalStorage", () => {
it("really adds, persists across a remount, and clears", async () => {
const user = userEvent.setup();
const { unmount } = render(<CartBadge />);
expect(screen.getByText("Cart: 0")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Add item" }));
expect(screen.getByText("Cart: 1")).toBeInTheDocument();
expect(window.localStorage.getItem("cart-count")).toBe("1");
unmount();
render(<CartBadge />);
expect(screen.getByText("Cart: 1")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Clear cart" }));
expect(screen.getByText("Cart: 0")).toBeInTheDocument();
});
});
solutions/ex05_restaurant_search_with_count.jsx
// Exercise 5 solution.
//
// The searchCount effect depends on debouncedQuery, never on the raw
// query state - that is the one detail that makes this a debounced
// search instead of a search-on-every-keystroke with extra steps.
import { useEffect, useState } from "react";
function useDebounce(value, delayMs) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timeoutId = setTimeout(() => setDebouncedValue(value), delayMs);
return () => clearTimeout(timeoutId);
}, [value, delayMs]);
return debouncedValue;
}
export function RestaurantSearchWithCount() {
const [query, setQuery] = useState("");
const [searchCount, setSearchCount] = useState(0);
const debouncedQuery = useDebounce(query, 400);
// oxlint's react(set-state-in-effect) warns here on purpose: this is the
// legitimate exception to Part 6's "don't use an effect for derived
// state" rule - searchCount is not computable from debouncedQuery
// during render (it is a running count of how many TIMES it has
// settled, an external-ish fact, not debouncedQuery's current value),
// so synchronizing it with an effect is correct here, not an anti-pattern.
useEffect(() => {
if (debouncedQuery.trim() === "") return;
setSearchCount((current) => current + 1);
}, [debouncedQuery]);
return (
<div>
<input value={query} onChange={(event) => setQuery(event.target.value)} />
<p>Searches run: {searchCount}</p>
</div>
);
}
solutions/ex05_restaurant_search_with_count.test.jsx
import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RestaurantSearchWithCount } from "./ex05_restaurant_search_with_count.jsx";
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
describe("RestaurantSearchWithCount only counts a search once the debounced value settles", () => {
it("really stays at 0 while typing, and counts exactly one search for the final value", () => {
render(<RestaurantSearchWithCount />);
const input = screen.getByRole("textbox");
fireEvent.change(input, { target: { value: "p" } });
act(() => vi.advanceTimersByTime(100));
fireEvent.change(input, { target: { value: "pi" } });
act(() => vi.advanceTimersByTime(100));
fireEvent.change(input, { target: { value: "piz" } });
expect(screen.getByText("Searches run: 0")).toBeInTheDocument();
act(() => vi.advanceTimersByTime(400));
expect(screen.getByText("Searches run: 1")).toBeInTheDocument();
});
});
solutions/ex06_cart_sync.jsx
// Exercise 6 solution.
//
// HeaderCartIconBroken and CartSidePanelBroken each call useLocalStorage
// independently - two calls to the same hook, two completely separate
// useState slots. Reading the same localStorage KEY only matters the
// moment either one re-mounts and re-reads it; it does nothing to keep
// two already-mounted instances in sync with each other.
//
// The fix is not a different hook - it is the Part 3 lifting-state-up
// move, applied to a hook's return value: call the hook exactly ONCE, in
// a shared parent, and pass the value (and a function to change it) down
// as props to both children.
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = window.localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
export function HeaderCartIconBroken() {
const [count, setCount] = useLocalStorage("cart-count", 0);
return (
<div>
<p>Header icon - Cart: {count}</p>
<button onClick={() => setCount((current) => current + 1)}>Add item</button>
</div>
);
}
export function CartSidePanelBroken() {
const [count] = useLocalStorage("cart-count", 0);
return <p>Side panel - Cart: {count}</p>;
}
export function HeaderCartIconFixed({ count, addItem }) {
return (
<div>
<p>Header icon - Cart: {count}</p>
<button onClick={addItem}>Add item</button>
</div>
);
}
export function CartSidePanelFixed({ count }) {
return <p>Side panel - Cart: {count}</p>;
}
// CartLayoutFixed is the shared parent: it calls useLocalStorage exactly
// ONCE and hands the one resulting value (and a function to change it)
// down to both children as props - the actual fix, not a different hook.
export function CartLayoutFixed() {
const [count, setCount] = useLocalStorage("cart-count", 0);
function addItem() {
setCount((current) => current + 1);
}
return (
<div>
<HeaderCartIconFixed count={count} addItem={addItem} />
<CartSidePanelFixed count={count} />
</div>
);
}
solutions/ex06_cart_sync.test.jsx
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it } from "vitest";
import { CartLayoutFixed, CartSidePanelBroken, HeaderCartIconBroken } from "./ex06_cart_sync.jsx";
beforeEach(() => {
window.localStorage.clear();
});
describe("HeaderCartIconBroken and CartSidePanelBroken each own independent state", () => {
it("really desyncs - adding an item in one never updates the other", async () => {
const user = userEvent.setup();
render(
<div>
<HeaderCartIconBroken />
<CartSidePanelBroken />
</div>,
);
await user.click(screen.getByRole("button", { name: "Add item" }));
expect(screen.getByText("Header icon - Cart: 1")).toBeInTheDocument();
expect(screen.getByText("Side panel - Cart: 0")).toBeInTheDocument();
});
});
describe("CartLayoutFixed lifts the one useLocalStorage call up to a shared parent", () => {
it("really keeps both children in sync, because they share one state value", async () => {
const user = userEvent.setup();
render(<CartLayoutFixed />);
const header = screen.getByText("Header icon - Cart: 0").parentElement;
await user.click(within(header).getByRole("button", { name: "Add item" }));
expect(screen.getByText("Header icon - Cart: 1")).toBeInTheDocument();
expect(screen.getByText("Side panel - Cart: 1")).toBeInTheDocument();
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Copying the same useState + useEffect pair into a second (or third) component |
Two copies of the same logic have to be kept in sync by hand forever - a fix to one is easy to forget in the other | Extract it into a useXyz function once both components need the same behavior (Section 1-2) |
Calling a hook inside an if, a loop, or after an early return |
The number (or order) of hook calls can change between renders - React loses track of which state belongs to which call, and throws | Call every hook unconditionally at the top level; move the condition into the returned JSX instead (Section 4) |
| Calling a hook from a plain helper function, or from inside a callback/condition | Only components and other custom hooks are allowed to call hooks - anything else breaks React's ability to track call order the same way | Keep hook calls inside a component's or custom hook's top level only; pass data in and out as plain arguments/return values everywhere else |
| Assuming two components calling the same custom hook share a value | Every call to a custom hook creates its own, independent state - exactly like two separate useState(0) calls never share a count |
If a value (not just logic) needs to be shared, lift the hook call itself up to a common parent and pass the value down as a prop (Section 3, Section 6's exercise) - or reach for useContext (Part 9) once that parent is many levels away |
Writing localStorage/timer/subscription logic by hand inside every component that needs it |
Same root cause as the first mistake - duplicated logic, this time wrapped around a real browser API instead of pure state | Package it into a hook once (useLocalStorage, useDebounce), the same way Section 5-6 do, and let every caller reuse it |
Quick recap
- A custom hook is a plain function that calls other hooks - nothing more. The
useprefix is a naming convention React's tooling relies on, not special syntax. - Extract a custom hook once the same stateful logic is typed more than once across components that otherwise have nothing to do with each other.
- The rules of hooks exist because React tracks hooks by call order: call every hook unconditionally, at the top level, only from a component or another hook - never inside an
if/loop/early-return, and never from a plain function. - Breaking the first rule throws a real, specific error ("Rendered fewer hooks than expected...") the moment the number of hook calls actually shifts between renders - not a style complaint, a crash.
- A custom hook shares reusable code; it does not, by itself, share a value across the components that call it - every call gets its own independent state.
useLocalStorageanduseDebounceshow that a hook can useuseEffect(with the correct cleanup/dependency array) internally, so every component that calls the hook gets that correctness for free, without writing the effect itself.
Checklist
- I can explain, in one sentence, what makes a plain function a "custom hook" instead of an ordinary helper function.
- I found (or wrote) the same
useState/useEffectlogic duplicated across two components, then extracted it into oneuseXyzhook both components call instead. - I reproduced the rules-of-hooks crash myself - called a hook conditionally, with another hook after it, and watched React throw on a rerender that changes the condition - then fixed it by calling both hooks unconditionally.
- I rendered two components that call the same custom hook, and proved (not just assumed) that each one's state is completely independent of the other's.
- I wrote (or used) a hook that calls
useEffectinternally, with a correct dependency array and cleanup function, and confirmed its caller never has to write that effect itself. - I can say exactly what does fix two components needing the same shared value, now that I know a custom hook by itself does not.