React Hooks完全指南:从基础到进阶

React Hooks完全指南:从基础到进阶

大家好,我是蔓蔓。React Hooks是React 16.8引入的一个革命性特性,它让我们能够在函数组件中使用状态和其他React特性。今天我来和大家分享React Hooks的完整用法。

基础Hooks

useState

javascript 复制代码
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('蔓蔓');

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <input 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
    </div>
  );
}

useEffect

javascript 复制代码
import { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUser = async () => {
      setLoading(true);
      const response = await fetch(`/api/users/${userId}`);
      const data = await response.json();
      setUser(data);
      setLoading(false);
    };

    fetchUser();

    // 清理函数
    return () => {
      console.log('Cleanup');
    };
  }, [userId]); // 依赖数组

  if (loading) return <div>Loading...</div>;
  
  return <div>{user.name}</div>;
}

useContext

javascript 复制代码
import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div>Theme: {theme}</div>;
}

进阶Hooks

useReducer

javascript 复制代码
import { useReducer } from 'react';

const initialState = { count: 0 };

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}

useCallback和useMemo

javascript 复制代码
import { useState, useCallback, useMemo } from 'react';

function expensiveCalculation(num) {
  console.log('Calculating...');
  return num * 2;
}

function App() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  // useMemo - 缓存计算结果
  const doubled = useMemo(() => expensiveCalculation(count), [count]);

  // useCallback - 缓存函数引用
  const handleClick = useCallback(() => {
    console.log('Clicked:', count);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Doubled: {doubled}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <input 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
        placeholder="Name"
      />
      <button onClick={handleClick}>Log</button>
    </div>
  );
}

useRef

javascript 复制代码
import { useRef, useEffect } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return <input ref={inputRef} />;
}

// 存储可变值
function Timer() {
  const intervalRef = useRef(null);
  const [count, setCount] = useState(0);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);

    return () => {
      clearInterval(intervalRef.current);
    };
  }, []);

  return <div>Count: {count}</div>;
}

自定义Hooks

javascript 复制代码
// useLocalStorage.js
import { useState, useEffect } from 'react';

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

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// 使用
function App() {
  const [name, setName] = useLocalStorage('name', '蔓蔓');
  
  return (
    <input 
      value={name} 
      onChange={(e) => setName(e.target.value)} 
    />
  );
}

Hooks规则

javascript 复制代码
// ✅ 正确:在函数顶层调用
function GoodComponent() {
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    console.log(count);
  });
  
  return <div>{count}</div>;
}

// ❌ 错误:在条件语句中调用
function BadComponent() {
  if (someCondition) {
    const [count, setCount] = useState(0); // ❌
  }
  
  return <div>Hello</div>;
}

// ✅ 正确:依赖数组包含所有依赖
function GoodEffect() {
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    const timer = setInterval(() => {
      console.log(count);
    }, 1000);
    
    return () => clearInterval(timer);
  }, [count]);
  
  return <div>{count}</div>;
}

总结

React Hooks让函数组件更强大:

  1. useState管理状态
  2. useEffect处理副作用
  3. useContext跨组件传递数据
  4. useReducer管理复杂状态
  5. useCallback和useMemo优化性能
  6. 自定义Hooks复用逻辑

技术应当有温度,好的Hooks使用能让代码更简洁优雅。

相关推荐
镜象科技1 小时前
AI情感大模型应用场景全解:从校园到医院再到企业的落地地图
人工智能
Joshua-a2 小时前
工程数学-理解卷积的含义_线性时不变系统的冲激响应与卷积
人工智能·深度学习
song5012 小时前
React Native for OpenHarmony 实战:三方库 react-native-css-transformer 的鸿蒙化适配指南
css·人工智能·深度学习·react native·transformer
老金带你玩AI6 小时前
ChatGPT dots,到底能替你操多少心?
人工智能
养肥胖虎6 小时前
CodeGraph学习笔记:给代码建索引,节省Token和时间
ai·codegraph·代码索引
AliCloudROS7 小时前
计算巢 X DeepSeek Harness — 云端智能体工作台
人工智能·阿里云
深蓝AI7 小时前
GitHub的Push一年涨4.9倍:AI Agent为什么逼它重做Git存储?
人工智能·github
stereohomology8 小时前
大模型的观点谨:StoryTold 「Crafting Apps」四件套 · 深度总览
人工智能·llm
运维行者_8 小时前
网络性能监控怎么做?从自动发现到根因分析的4个环节
运维·服务器·网络·人工智能·支持向量机
Su米苏8 小时前
Spring AI 中MCP 与普通 @Tool的区别
java·人工智能·spring