惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
GbyAI
GbyAI
aimingoo的专栏
aimingoo的专栏
L
LangChain Blog
I
InfoQ
D
Docker
F
Fortinet All Blogs
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
月光博客
月光博客
B
Blog
Engineering at Meta
Engineering at Meta
T
Tailwind CSS Blog
罗磊的独立博客
博客园_首页
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
D
DataBreaches.Net
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog RSS Feed
IT之家
IT之家
V
V2EX

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
From Axios to alova: how we cut 80 lines to 5
Scott Hu · 2026-06-01 · via DEV Community
Cover image for From Axios to alova: how we cut 80 lines to 5

Scott Hu

Frontend request code often involves repetitive state management. This article compares Axios and alova through a paginated list example, analyzing how request strategization reduces boilerplate and when it's a good fit.


The Pattern: Paginated List in Two Ways

A common requirement: fetch a user list with pagination.

Approach 1: Axios

const [data, setData] = useState([]);
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

const fetchUsers = async (currentPage) => {
  setLoading(true);
  setError(null);
  try {
    const res = await axios.get('/api/users', {
      params: { page: currentPage, pageSize: 10 },
    });
    setData(res.data.list);
    setTotal(res.data.total);
  } catch (e) {
    setError(e.message);
  } finally {
    setLoading(false);
  }
};

useEffect(() => { fetchUsers(page); }, [page]);

This pattern appears in nearly every data-fetching component. The actual business logic — GET /api/users — occupies a single line. The rest is infrastructure: state declarations, loading toggles, error handling, and effect management.

Approach 2: alova with usePagination

const {
  data, total, loading, error,
  page, pageSize, nextPage, prevPage,
} = usePagination(
  (page, pageSize) => alovaInstance.Get('/api/users', {
    params: { page, pageSize },
  }),
  { page: 1, pageSize: 10 }
);

Both implementations are functionally identical. The key difference is where the state management logic lives: in the component (Axios) vs. inside the hook (alova).

What Changed

Component of Axios version Handled by alova
loading state + toggling Managed internally by usePagination
error state + try/catch Managed internally by usePagination
data state + assignment Returned as reactive value
page state + change handler Built-in nextPage / prevPage
total state extraction Extracted from response automatically
useEffect dependency tracking Managed internally

The removed code shares one characteristic: it's infrastructure for the request pattern, not business logic. alova encapsulates this infrastructure into scenario-specific hooks.

Beyond Pagination

alova provides hooks for common request patterns:

useRequest — basic fetch

// Auto-fetch on mount
const { data, loading, error } = useRequest(getUserList());

// Manual trigger
const { send } = useRequest(createOrder, { immediate: false });

useWatcher — reactive fetch with debounce

const { data } = useWatcher(
  () => searchApi(keyword.value),
  [keyword],
  { debounce: 300 }
);

useForm — form submission

const { form, loading, send: submit, reset } = useForm(
  submitApi,
  { initialForm: { name: '', email: '' } }
);

All hooks share a consistent return interface (data, loading, error) while adding scenario-specific capabilities.

Code reduction across six common scenarios:

Scenario Axios (core lines) alova (core lines) Reduction
Paginated list ~30 6 ~80%
Search with debounce ~25 3 ~88%
Form submission ~30 3 ~90%
Polling / auto-refresh ~25 3 ~88%
Chained requests ~30 5 ~83%
File upload ~35 8 ~77%

Line counts reflect core logic only, excluding UI rendering and imports.

When to Use (And When Not To)

Good fit for:

  • Medium-to-large projects with many data-fetching pages
  • Teams wanting consistent request patterns across codebase
  • New projects where the abstraction can be established early

Less suitable for:

  • Small projects where the abstraction overhead outweighs the benefit
  • Teams already deeply invested in React Query or SWR — evaluate migration cost carefully
  • Non-standard request patterns that don't map well to existing hooks
  • Framework ecosystems outside of React/Vue/Svelte support

Other considerations:

  • Learning curve: Understanding the strategy hook paradigm takes initial investment
  • Debugging: The abstraction layer can add indirection when troubleshooting unexpected behavior
  • Ecosystem: alova's community and third-party integrations are smaller than Axios'
  • Migration path: The Method API mirrors Axios, enabling incremental adoption
// Nearly identical API
axios.get('/api/users', { params: { page: 1 } });
alovaInstance.Get('/api/users', { params: { page: 1 } });

Summary

Moving from Axios to alova is not about "switching HTTP libraries." It's about treating requests as composable scenarios rather than one-shot operations you wire up manually. Whether this abstraction is valuable depends on your project's specific needs — the code reduction is real, but so are the trade-offs.