Typorithm · medium

Custom Hooks

react-custom-hooksreactcustom-hookreusestateful-logic
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Custom Hooks

0%

Patterns

A custom hook is a function named use* that calls other hooks to package reusable stateful logic. Each component using it gets its own isolated state; it returns whatever the caller needs; hooks must be called at the top level, never conditionally.

A custom hook is just a function whose name begins with use and that calls built-in hooks like useState or useEffect. The use prefix lets React (and lint rules) enforce the rules of hooks on it.

Custom hooks share logic, not state. Every component that calls useOnline() gets its own independent state and effect — calling the hook twice creates two separate subscriptions, not a shared one.

A hook returns whatever the caller needs: a value, an array, or an object of values and setters. Like all hooks, it must be called at the top level of a component or another hook, never inside conditions or loops.

01

Name custom hooks use* so they may call hooks.

02

Each caller gets isolated state, not shared state.

03

Call hooks at the top level, never conditionally.

import { useEffect, useState } from "react";

function useOnline() {
  const [online, setOnline] = useState(true);
  useEffect(() => {
    const on = () => setOnline(true);
    window.addEventListener("online", on);
    return () => window.removeEventListener("online", on);
  }, []);
  return online;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. use* name

A custom hook is a function whose name starts with use, signalling that it may call other hooks.

function useOnline() {

2. Internal state

The hook holds its own state with useState; each caller gets an isolated copy.

const [online, setOnline] = useState(true);

3. Subscribe

The effect wires up a browser listener that updates state when connectivity returns.

window.addEventListener("online", on);

4. Cleanup

Returning a cleanup function removes the listener when the component unmounts.

return () => window.removeEventListener("online", on);

5. Return value

The hook returns whatever the caller needs — here, the current online status.

return online;

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Custom Hooks: Lesson & Practice · Typorithm | ApplyDjinn