Skip to content

自定义 Hook

Extracting reusable stateful logic 到自定义 Hook and 规则的 Hook.

你将学到

  • 什么自定义 Hook 是 and 为什么它们是 powerful
  • 如何 extract stateful logic 到 reusable Hook
  • 规则的 Hook and naming 约定
  • Composing Hook 内部 other Hook

概念讲解

What Are Custom Hooks?

A custom hook is a JavaScript function whose name starts with use and that may call other hooks inside it. Custom hooks let you extract component logic into reusable functions, just like regular functions extract reusable calculations. If you find yourself copying the same useState and useEffect patterns across multiple components, you can extract that logic into a custom hook and reuse it. This is one of the most powerful features of React.

Extracting Logic

For example, a useWindowSize hook could encapsulate the logic for tracking the window dimensions. A useLocalStorage hook could sync a state value to localStorage. A useFetch hook could handle loading, data, and error states for API calls. Each hook returns whatever the consuming component needs — state values, handlers, or an object with multiple properties. The hook manages its own state internally, and each component that calls the hook gets its own independent state.

The Rules of Hooks

Custom hooks must follow the Rules of Hooks: only call hooks at the top level (not inside loops, conditions, or nested functions), and only call hooks from React function components or other custom hooks. The use prefix is not just convention — React's linter plugin relies on it to enforce the rules. Never call a hook inside a regular function that is not a component or hook.

Composing Hooks

Custom hooks can call other custom hooks, creating composable layers of logic. A useUserData hook might call useFetch and useLocalStorage. This composition lets you build complex behavior from simple, testable pieces. Keep hooks focused on one concern, and name them descriptively. Test hooks in isolation with React Testing Library or by rendering a small test component.

Return Value Patterns

Custom hooks can return a single value, an array (like useState), or an object with named properties. Returning an array lets consumers rename the values: const [数据, 加载] = useFetch(URL). Returning an object is better when there are many properties or when consumers only need some: const { 数据, 错误 } = useFetch(URL). Choose the pattern that makes the consuming code clearest.

示例代码

              import { useState, useEffect } from "react";

// Custom hook: tracks a value synced to localStorage.
function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

// Custom hook: tracks window size.
function useWindowSize() {
  const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });
  useEffect(() => {
    const handler = () => setSize({ width: window.innerWidth, height: window.innerHeight });
    window.addEventListener("resize", handler);
    return () => window.removeEventListener("resize", handler);
  }, []);
  return size;
}

// Using both custom hooks in a component.
function App() {
  const [name, setName] = useLocalStorage("username", "Guest");
  const { width, height } = useWindowSize();
  return (
    <div>
      <p>Window: {width} x {height}</p>
      <input value={name} onChange={e => setName(e.target.value)} />
    </div>
  );
}
            

useLocalStorage and useWindowSize 是自定义 Hook 那个 encapsulate reusable logic. 每个组件 calling 它们获取 independent 状态. Hook compose naturally.

动手试一试

  • JSON Formatter

    自定义 Hook 经常返回对象 — 格式到 inspect 它们的 shape.

  • Code Diff

    Compare Hook implementations 当 refactoring shared logic.

常见错误

错误写法

不开始 Hook name 使用 'use'

正确做法

React's linter and 规则的 Hook rely on 'use' prefix. 函数那个 calls Hook 必须是 named useSomething. 不使用它, linter cannot detect Hook violations.

错误写法

Breaking 规则的 Hook 内部自定义 Hook

正确做法

自定义 Hook 必须 call Hook at 顶部 level 仅 — 从不内部条件, 循环, or nested 函数. 相同规则 apply 内部自定义 Hook as 内部组件.

练习 自定义 Hook

5 个练习

练习 自定义 Hook

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误