react-hooks-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

React Hooks Patterns

React Hooks 模式

Master modern React hooks patterns for building scalable, maintainable applications with proper state management, side effects, and custom logic reuse.
掌握用于构建可扩展、可维护应用的现代React Hooks模式,包括合适的状态管理、副作用处理和自定义逻辑复用。

Common Hooks

常用Hooks

useState

useState

typescript
const [count, setCount] = useState(0);
const [user, setUser] = useState<User | null>(null);

// Functional updates
setCount(prev => prev + 1);
typescript
const [count, setCount] = useState(0);
const [user, setUser] = useState<User | null>(null);

// 函数式更新
setCount(prev => prev + 1);

useEffect

useEffect

typescript
useEffect(() => {
  // Side effect
  const subscription = api.subscribe();
  return () => subscription.unsubscribe();
}, [dependencies]);
typescript
useEffect(() => {
  // 副作用
  const subscription = api.subscribe();
  return () => subscription.unsubscribe();
}, [dependencies]);

useContext

useContext

typescript
const theme = useContext(ThemeContext);
typescript
const theme = useContext(ThemeContext);

useMemo & useCallback

useMemo & useCallback

typescript
const memoized = useMemo(() => expensive(a, b), [a, b]);
const callback = useCallback(() => doSomething(a), [a]);
typescript
const memoized = useMemo(() => expensive(a, b), [a, b]);
const callback = useCallback(() => doSomething(a), [a]);

Custom Hooks

自定义Hooks

typescript
function useFetch<T>(url: string) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);

  return { data, loading, error };
}
typescript
function useFetch<T>(url: string) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);

  return { data, loading, error };
}

Best Practices

最佳实践

  1. Always provide dependency arrays
  2. Use useCallback for event handlers
  3. Create custom hooks for reusable logic
  4. Keep components focused and small
  5. Use TypeScript for type safety
  6. Clean up effects properly
  7. Avoid excessive use of useEffect
  1. 始终提供依赖数组
  2. 对事件处理函数使用useCallback
  3. 为可复用逻辑创建自定义Hooks
  4. 保持组件聚焦且轻量化
  5. 使用TypeScript保障类型安全
  6. 正确清理副作用
  7. 避免过度使用useEffect

Resources

资源