Bitpath

Lesson 1 · Unit 04

Custom hooks

Why hooks have rules, how to extract your own, and when refs, useMemo and useCallback help.

13 exercisesabout 3 min

What you practise

  • The rules of hooks and why they exist, extracting a hook, useRef, useMemo and useCallback and when they help

Try a question from this lesson

Pick one

Neither call says which piece of state it wants. How does React know that the first call owns "Ada" and the second owns 36?

TypeScript
const [name, setName] = useState('Ada');
const [age, setAge] = useState(36);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The rules of hooks

Two rules keep the slots lined up. Call hooks only at the top level of a component: not inside a condition, a loop or a nested function, and not after an early return. And call them only from components or from other hooks. Put the condition inside the hook, never the hook inside the condition. A linter checks both rules.

Concept

Custom hooks

When two components need the same stateful logic, move it into a function whose name starts with use. A custom hook is an ordinary function that calls other hooks and returns whatever its callers need. The rules of hooks apply inside it, and the use name is how the linter knows.

TypeScript
function useToggle(start = false) {
  const [on, setOn] = useState(start);
  const flip = () => setOn(v => !v);
  return [on, flip] as const;
}
// in any component:
// const [open, flip] = useToggle();

10 more exercises in the app

  • 5× multiple choice
  • 2× true or false
  • 1× order the lines
  • 1× type the answer
  • 1× fill the blanks

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy