Custom Hooks

Last updated: 2026-11-02

Custom Hooks Custom Hooks

A custom hook is an ordinary function whose name starts with use, which may call other hooks inside and turns stateful logic such as requests, debouncing, persistence or toggling into a reusable unit. Every call owns its own state — what gets reused is the logic, not the state itself. It is the standard way to share behaviour between components without sharing data, and it keeps each component's state local and easy to reason about.

GroupComponent Patterns
KindHook
SinceReact 16.8

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

// the name must start with use so that ESLint can check the rules of hooks
function useToggle(initial = false) {
  const [on, setOn] = useState(initial)
  const toggle = () => setOn(v => !v)
  return [on, toggle]        // the return shape is up to you: an array or an object
}

Returns:No fixed signature — you define it. By convention it returns a [value, action] tuple, or an object holding a set of actions.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

The two buttons toggle independently — Lamp and Fan each hold their own on state that never interferes with the other, yet both share the same useToggle logic.

💡 Key Points

💡 Tip Two components calling the same custom hook keep completely separate state — a hook reuses logic, it does not share state.
ℹ️ Info When you do need shared state, lift the state up or move it into a Context; a custom hook can still compose useState and useEffect inside.
⚠️ Warning Only call it at the top level of a component or another hook, never inside an if, a loop or a plain function — the same rules as every hook.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q Is the state inside a custom hook shared?
A No. Every call creates its own separate state, more like functional inheritance of logic than a singleton.
Q Should I return an array or an object?
A Return an array when there are two or three values with clear semantics so that destructuring can rename them; return an object when there are many actions or room to grow.
Q Does the name really have to start with use?
A Strongly recommended: it is the convention React and ESLint rely on to recognise hooks and enforce the rules of hooks, and breaking it disables the whole lint check.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏