Convert Figma logo to code with AI

alibaba logohooks

A high-quality & reliable React Hooks library. https://ahooks.pages.dev/

13,877
2,684
13,877
198

Top Related Projects

41,502

React Hooks — 👍

A collection of modern, server-safe React hooks – from the ui.dev team

30,209

React Hooks for Data Fetching

41,619

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

46,119

🐻 Bear necessities for state management in React

Quick Overview

Alibaba/hooks is a high-quality, lightweight React Hooks library developed by Alibaba. It provides a collection of essential and advanced hooks to simplify React development, improve code reusability, and enhance application performance.

Pros

  • Comprehensive collection of hooks for various common use cases
  • Well-documented with clear examples and API references
  • Lightweight and modular, allowing for easy integration and tree-shaking
  • Regular updates and maintenance from a reputable company (Alibaba)

Cons

  • Some hooks may have a learning curve for developers new to React Hooks
  • Limited community contributions compared to more popular React hook libraries
  • Potential for over-reliance on third-party hooks instead of custom solutions
  • Documentation is primarily in Chinese, which may be challenging for non-Chinese speakers

Code Examples

  1. Using the useRequest hook for data fetching:
import { useRequest } from 'ahooks';

function UserList() {
  const { data, error, loading } = useRequest(() => 
    fetch('/api/users').then(res => res.json())
  );

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  return <ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}
  1. Implementing a debounced input with useDebounceFn:
import { useDebounceFn } from 'ahooks';

function SearchInput() {
  const { run } = useDebounceFn(
    (value) => {
      console.log('Searching for:', value);
    },
    { wait: 500 }
  );

  return <input onChange={(e) => run(e.target.value)} />;
}
  1. Managing local storage with useLocalStorageState:
import { useLocalStorageState } from 'ahooks';

function ThemeToggle() {
  const [theme, setTheme] = useLocalStorageState('theme', 'light');

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Toggle Theme (Current: {theme})
    </button>
  );
}

Getting Started

To start using alibaba/hooks in your React project:

  1. Install the package:

    npm install ahooks
    

    or

    yarn add ahooks
    
  2. Import and use the hooks in your components:

    import { useRequest, useToggle } from 'ahooks';
    
    function MyComponent() {
      const [state, { toggle }] = useToggle();
      // ... use the hooks in your component logic
    }
    

For more detailed usage and a complete list of available hooks, refer to the official documentation.

Competitor Comparisons

41,502

React Hooks — 👍

Pros of react-use

  • Larger collection of hooks (100+) compared to hooks (~30)
  • More frequent updates and active community contributions
  • Includes hooks for advanced use cases like animations and sensors

Cons of react-use

  • Less comprehensive documentation and examples
  • May include unnecessary hooks for some projects, potentially increasing bundle size
  • Some hooks might be less optimized or have edge cases compared to hooks

Code Comparison

react-use:

import { useToggle, useCounter } from 'react-use';

const [isOn, toggleOn] = useToggle(false);
const [count, { inc, dec, reset }] = useCounter(0);

hooks:

import { useToggle, useCounter } from 'ahooks';

const [state, { toggle }] = useToggle();
const [count, { inc, dec, set, reset }] = useCounter(0);

Both libraries offer similar functionality for basic hooks, but react-use tends to have more concise implementations. hooks often provides more options and methods for each hook, potentially offering more flexibility at the cost of a slightly more verbose API.

A collection of modern, server-safe React hooks – from the ui.dev team

Pros of usehooks

  • Simpler and more focused, offering a curated set of essential hooks
  • Easier to understand and implement for beginners
  • Lightweight, with minimal dependencies

Cons of usehooks

  • Fewer hooks available compared to hooks
  • Less comprehensive documentation and examples
  • Limited TypeScript support

Code Comparison

hooks:

import { useRequest } from 'ahooks';

function App() {
  const { data, error, loading } = useRequest(fetchUser);
  // ...
}

usehooks:

import { useAsync } from 'usehooks';

function App() {
  const { value, loading, error } = useAsync(() => fetchUser());
  // ...
}

Both repositories provide custom React hooks, but they differ in scope and implementation. hooks offers a more extensive collection of hooks with advanced features and TypeScript support, while usehooks focuses on simplicity and ease of use.

hooks is maintained by Alibaba and has a larger community, resulting in more frequent updates and better documentation. It also includes hooks for complex scenarios like state management and data fetching.

usehooks, on the other hand, is more suitable for developers who prefer a minimalist approach and want to quickly integrate common hooks into their projects. It's ideal for smaller applications or those looking to keep their dependencies light.

Ultimately, the choice between these libraries depends on the project's requirements, the developer's familiarity with React hooks, and the desired level of complexity and functionality.

30,209

React Hooks for Data Fetching

Pros of SWR

  • Lightweight and focused on data fetching, with a smaller bundle size
  • Built-in support for real-time and optimistic UI updates
  • Seamless integration with Next.js and other React frameworks

Cons of SWR

  • Limited to data fetching and caching, while Hooks offers a broader range of utility hooks
  • Less extensive documentation and examples compared to Hooks
  • Smaller community and ecosystem compared to Alibaba's offering

Code Comparison

SWR:

import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

Hooks:

import { useRequest } from 'ahooks'

function Profile() {
  const { data, error, loading } = useRequest('/api/user')
  if (error) return <div>failed to load</div>
  if (loading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

Both libraries provide similar functionality for data fetching, but SWR focuses more on this specific use case, while Hooks offers a wider range of utility hooks for various purposes. SWR's API is slightly more concise, but Hooks provides more flexibility and options for advanced use cases.

41,619

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

Pros of Query

  • More comprehensive data fetching and state management solution
  • Better support for server-side rendering and real-time updates
  • Extensive documentation and larger community support

Cons of Query

  • Steeper learning curve due to more complex API
  • Potentially overkill for simpler applications
  • Requires additional setup and configuration

Code Comparison

Query:

const { data, isLoading, error } = useQuery('todos', fetchTodos)

if (isLoading) return 'Loading...'
if (error) return 'An error occurred: ' + error.message
return <div>{data.map(todo => <Todo key={todo.id} {...todo} />)}</div>

Hooks:

const { data, loading, error } = useRequest(fetchTodos)

if (loading) return 'Loading...'
if (error) return 'An error occurred: ' + error.message
return <div>{data.map(todo => <Todo key={todo.id} {...todo} />)}</div>

Summary

Query offers a more robust solution for data fetching and state management, with better support for complex scenarios and real-time updates. However, it comes with a steeper learning curve and may be excessive for simpler applications. Hooks provides a more straightforward API and is easier to integrate into existing projects, but may lack some advanced features found in Query. The choice between the two depends on the specific requirements of your project and the level of complexity you're dealing with.

46,119

🐻 Bear necessities for state management in React

Pros of zustand

  • Simpler API with less boilerplate compared to hooks
  • Better performance for large state updates
  • Supports middleware and devtools out of the box

Cons of zustand

  • Less comprehensive set of pre-built hooks
  • Steeper learning curve for developers familiar with React's built-in hooks
  • May require additional setup for TypeScript users

Code Comparison

zustand:

import create from 'zustand'

const useStore = create(set => ({
  count: 0,
  increment: () => set(state => ({ count: state.count + 1 })),
}))

hooks:

import { useSetState } from 'ahooks'

const [state, setState] = useSetState({ count: 0 })
const increment = () => setState(prev => ({ count: prev.count + 1 }))

Both libraries aim to simplify state management in React applications, but they take different approaches. zustand focuses on providing a minimal, flexible state management solution with a single store, while hooks offers a collection of ready-to-use React hooks for various common scenarios. zustand may be more suitable for larger applications with complex state requirements, while hooks might be preferred for smaller projects or when developers need quick access to a wide range of utility hooks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

A high-quality & reliable React Hooks library.

NPM version NPM downloads npm npm Coverage Status gzip size Percentage of issues still open Average time to resolve an issue GitHub

English | 简体中文

📚 Documentation

✨ Features

  • Easy to learn and use
  • Supports SSR
  • Special treatment for functions, avoid closure problems
  • Contains a large number of advanced Hooks that are refined from business scenarios
  • Contains a comprehensive collection of basic Hooks
  • Written in TypeScript with predictable static types

📦 Install

$ npm install --save ahooks
# or
$ yarn add ahooks
# or
$ pnpm add ahooks
# or
$ bun add ahooks

🔨 Usage

import { useRequest } from 'ahooks';

💻 Online Demo

Edit demo for ahooks

🤝 Contributing

$ git clone git@github.com:alibaba/hooks.git
$ cd hooks
$ pnpm run init
$ pnpm start

Open your browser and visit http://127.0.0.1:8000

We welcome all contributions, please read our CONTRIBUTING.MD first, let's build a better hooks library together.

Thanks to all the contributors:

contributors

👥 Discuss

NPM DownloadsLast 30 Days