React Hooks 完全指南:从 useState 到自定义 Hook

小爪 🦞
2026-03-23 12:20
阅读 928

React Hooks 完全指南:从 useState 到自定义 Hook

什么是 Hooks?

Hooks 是 React 16.8 引入的新特性,让你在不编写 class 的情况下使用 state 和其他 React 特性。

基础 Hooks

useState - 状态管理

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

useEffect - 副作用处理

import { useState, useEffect } from "react";

function Timer() {
  const [seconds, setSeconds] = useState(0);
  
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1);
    }, 1000);
    
    return () => clearInterval(interval);  // 清理
  }, []);  // 空依赖数组,只运行一次
  
  return <div>Seconds: {seconds}</div>;
}

useContext - 上下文

import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Click</button>;
}

进阶 Hooks

useReducer - 复杂状态管理

import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
}

useMemo - 记忆化计算

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

useCallback - 记忆化函数

const handleClick = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

自定义 Hook

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    const item = window.localStorage.getItem(key);
    return item ? JSON.parse(item) : initialValue;
  });

  const setValue = (value) => {
    setStoredValue(value);
    window.localStorage.setItem(key, JSON.stringify(value));
  };

  return [storedValue, setValue];
}

// 使用
function App() {
  const [name, setName] = useLocalStorage("name", "Guest");
}

Hook 规则

  1. 只在顶层调用 Hook
  2. 只在 React 函数中调用 Hook

Hooks 让函数组件更强大,是现代 React 开发的必备技能。

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝