Convert Figma logo to code with AI

kitze logoreact-hanger

A collection of useful React hooks

1,935
76
1,935
10

Top Related Projects

41,752

React Hooks — 👍

Awesome React Hooks

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

🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥

1,906

React hooks done right, for browser and SSR.

13,985

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

Quick Overview

React Hanger is a custom hooks library for React applications. It provides a collection of useful hooks that simplify state management and common UI interactions, making it easier to build React components with less boilerplate code.

Pros

  • Simplifies state management with easy-to-use custom hooks
  • Reduces boilerplate code in React components
  • Provides a wide range of hooks for various use cases
  • Lightweight and easy to integrate into existing projects

Cons

  • May introduce unnecessary dependencies for simple projects
  • Some hooks might have a learning curve for developers new to custom hooks
  • Limited documentation for advanced use cases
  • Potential performance impact if overused in a large application

Code Examples

  1. Using the useBoolean hook:
import { useBoolean } from 'react-hanger';

function ToggleComponent() {
  const showContent = useBoolean(false);

  return (
    <div>
      <button onClick={showContent.toggle}>
        {showContent.value ? 'Hide' : 'Show'}
      </button>
      {showContent.value && <p>Hidden content</p>}
    </div>
  );
}
  1. Using the useInput hook:
import { useInput } from 'react-hanger';

function InputComponent() {
  const name = useInput('');

  return (
    <div>
      <input {...name.bindToInput} />
      <p>Hello, {name.value}!</p>
    </div>
  );
}
  1. Using the useArray hook:
import { useArray } from 'react-hanger';

function TodoList() {
  const todos = useArray(['Learn React', 'Build an app']);

  return (
    <div>
      <ul>
        {todos.value.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
      <button onClick={() => todos.push('New todo')}>Add Todo</button>
    </div>
  );
}

Getting Started

To start using React Hanger in your project, follow these steps:

  1. Install the package:
npm install react-hanger
  1. Import and use the hooks in your React components:
import { useBoolean, useInput, useArray } from 'react-hanger';

function MyComponent() {
  const isLoading = useBoolean(false);
  const username = useInput('');
  const items = useArray([]);

  // Use the hooks in your component logic
  // ...

  return (
    // Your JSX here
  );
}

Competitor Comparisons

41,752

React Hooks — 👍

Pros of react-use

  • Larger collection of hooks (100+) covering a wide range of use cases
  • More frequent updates and active maintenance
  • Includes TypeScript definitions out of the box

Cons of react-use

  • Larger bundle size due to the extensive collection of hooks
  • Steeper learning curve with more hooks to understand and choose from

Code Comparison

react-use:

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

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

react-hanger:

import { useBoolean, useNumber } from 'react-hanger';

const isOn = useBoolean(false);
const count = useNumber(0);

Both libraries provide similar functionality, but react-use offers a more extensive set of hooks with slightly different syntax. react-hanger focuses on simplicity and ease of use, while react-use provides a comprehensive toolkit for various React development scenarios.

Awesome React Hooks

Pros of awesome-react-hooks

  • Comprehensive collection of React hooks from various sources
  • Regularly updated with new hooks and resources
  • Includes categorization and descriptions for easy navigation

Cons of awesome-react-hooks

  • Not a standalone library, requires additional setup to use hooks
  • May include outdated or unmaintained hooks
  • Lacks standardization across different hook implementations

Code Comparison

react-hanger:

import { useInput } from 'react-hanger';

const MyComponent = () => {
  const input = useInput('');
  return <input value={input.value} onChange={input.onChange} />;
};

awesome-react-hooks (example from useHooks):

import { useInput } from 'use-hooks';

const MyComponent = () => {
  const [value, setValue] = useInput('');
  return <input value={value} onChange={setValue} />;
};

Summary

react-hanger is a focused library providing a set of custom hooks, while awesome-react-hooks is a curated list of hooks from various sources. react-hanger offers a more consistent API and immediate usability, whereas awesome-react-hooks provides a wider range of options but requires more setup and evaluation of individual hooks.

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

Pros of usehooks

  • Larger collection of hooks (30+) covering a wide range of use cases
  • Well-documented with examples and explanations for each hook
  • Regularly updated and maintained

Cons of usehooks

  • Less focused on state management compared to react-hanger
  • Some hooks may be considered too simple or unnecessary for experienced developers

Code Comparison

react-hanger:

const [value, setValue] = useInput('');
const [count, { increment, decrement }] = useNumber(0);

usehooks:

const [value, setValue] = useInput('');
const [count, setCount] = useState(0);
const increment = () => setCount(c => c + 1);
const decrement = () => setCount(c => c - 1);

Summary

Both react-hanger and usehooks provide useful custom hooks for React applications. react-hanger focuses more on state management with specialized hooks, while usehooks offers a broader range of utility hooks. react-hanger's API is often more concise, but usehooks provides more extensive documentation and examples. The choice between the two depends on the specific needs of your project and personal preference for API design.

🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥

Pros of beautiful-react-hooks

  • More extensive collection of hooks (30+) compared to react-hanger's 12
  • Includes hooks for DOM events, animations, and network requests
  • Better documentation with examples and TypeScript support

Cons of beautiful-react-hooks

  • Larger bundle size due to more hooks and dependencies
  • Some hooks may be less performant than react-hanger equivalents
  • Steeper learning curve due to the larger API surface

Code Comparison

beautiful-react-hooks:

import { useWindowResize } from 'beautiful-react-hooks';

const MyComponent = () => {
  const { width, height } = useWindowResize();
  return <div>Window size: {width}x{height}</div>;
};

react-hanger:

import { useWindowSize } from 'react-hanger';

const MyComponent = () => {
  const { width, height } = useWindowSize();
  return <div>Window size: {width}x{height}</div>;
};

Both libraries provide similar functionality for common hooks, but beautiful-react-hooks offers a wider range of specialized hooks. react-hanger focuses on core state management hooks, while beautiful-react-hooks extends to cover more use cases. The choice between them depends on the specific needs of your project and the trade-offs you're willing to make in terms of bundle size and API complexity.

1,906

React hooks done right, for browser and SSR.

Pros of react-hookz/web

  • Larger collection of hooks (50+) covering a wider range of use cases
  • More active development and maintenance, with frequent updates
  • Comprehensive documentation and examples for each hook

Cons of react-hookz/web

  • Steeper learning curve due to the larger number of hooks
  • Potentially larger bundle size if importing the entire package

Code Comparison

react-hanger:

const [value, setValue] = useNumber(0)
setValue(5)
setValue(n => n + 1)

react-hookz/web:

const [value, { set, inc }] = useNumber(0)
set(5)
inc()

Both libraries provide similar functionality for managing numeric state, but react-hookz/web offers more granular control with separate methods for setting and incrementing the value.

Summary

react-hookz/web offers a more comprehensive set of hooks and active development, making it suitable for projects requiring a wide range of utility hooks. However, react-hanger may be preferable for simpler projects or those prioritizing a smaller bundle size and easier learning curve. The choice between the two depends on the specific needs of your project and development team preferences.

13,985

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

Pros of hooks

  • More comprehensive set of hooks, covering a wider range of use cases
  • Better documentation and examples, including a dedicated website
  • Active development and maintenance by a large company (Alibaba)

Cons of hooks

  • Larger package size due to the extensive collection of hooks
  • Steeper learning curve for developers due to the number of available hooks

Code comparison

react-hanger:

import { useInput } from 'react-hanger';

const MyComponent = () => {
  const input = useInput('');
  return <input value={input.value} onChange={input.onChange} />;
};

hooks:

import { useInput } from 'ahooks';

const MyComponent = () => {
  const [value, { onChange }] = useInput('');
  return <input value={value} onChange={onChange} />;
};

Summary

hooks offers a more extensive collection of hooks and better documentation, making it suitable for larger projects with diverse requirements. react-hanger, on the other hand, provides a simpler and more lightweight solution for basic hook needs. The code comparison shows that both libraries offer similar functionality for common hooks like useInput, with slight differences in implementation and usage.

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

🙋‍♂️ Made by @thekitze

Other projects:

  • 💻 Sizzy - A browser for designers and developers, focused on responsive design
  • 🏫 React Academy - Interactive React and GraphQL workshops
  • 🔮 Glink - Changelogs, Roadmap, User Requests
  • 🐶 Benji - Ultimate wellness and productivity platform
  • 🤖 JSUI - A powerful UI toolkit for managing JavaScript apps
  • 📹 YouTube Vlog - Follow my journey

Zero To Shipped

react-hanger

npm version

All Contributors

Set of a helpful hooks, for different specific to some primitives types state changing helpers.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Andrey Los

🤔 🚇 ⚠️ 💻

Praneet Rohida

🚇 ⚠️ 💻

This project follows the all-contributors specification. Contributions of any kind welcome!


Has two APIs:

  • First and original from v1 is based on object destructuring e.g. const { value, toggle } = useBoolean(false) (Docs below)
  • Second API (recommended why?) is based on more idiomatic to React hooks API, e.g. like useState with array destructuring const [value, actions] = useBoolean(false) (Docs)

Install

yarn add react-hanger

Usage

import React, { Component } from 'react';

import { useInput, useBoolean, useNumber, useArray, useOnMount, useOnUnmount } from 'react-hanger';

const App = () => {
  const newTodo = useInput('');
  const showCounter = useBoolean(true);
  const limitedNumber = useNumber(3, { lowerLimit: 0, upperLimit: 5 });
  const counter = useNumber(0);
  const todos = useArray(['hi there', 'sup', 'world']);

  const rotatingNumber = useNumber(0, {
    lowerLimit: 0,
    upperLimit: 4,
    loop: true,
  });

  return (
    <div>
      <button onClick={showCounter.toggle}> toggle counter </button>
      <button onClick={() => counter.increase()}> increase </button>
      {showCounter.value && <span> {counter.value} </span>}
      <button onClick={() => counter.decrease()}> decrease </button>
      <button onClick={todos.clear}> clear todos </button>
      <input type="text" value={newTodo.value} onChange={newTodo.onChange} />
    </div>
  );
};

Example

Edit react-hanger example

API reference (object destructuring)

How to import?

import { useBoolean } from 'react-hanger' // will import all of functions
import useBoolean from 'react-hanger/useBoolean' // will import only this function

useStateful

Just an alternative syntax to useState, because it doesn't need array destructuring. It returns an object with value and a setValue method.

const username = useStateful('test');

username.setValue('tom');
console.log(username.value);

useBoolean

const showCounter = useBoolean(true);

Methods:

  • toggle
  • setTrue
  • setFalse

useNumber

const counter = useNumber(0);
const limitedNumber = useNumber(3, { upperLimit: 5, lowerLimit: 3 });
const rotatingNumber = useNumber(0, {
  upperLimit: 5,
  lowerLimit: 0,
  loop: true,
});

Methods:

Both increase and decrease take an optional amount argument which is 1 by default, and will override the step property if it's used in the options.

  • increase(amount = 1)
  • decrease(amount = 1 )

Options:

  • lowerLimit
  • upperLimit
  • loop
  • step - sets the increase/decrease amount of the number upfront, but it can still be overriden by number.increase(3) or number.decrease(5)

useInput

const newTodo = useInput('');
<input value={newTodo.value} onChange={newTodo.onChange} />
<input {...newTodo.eventBind} />
<Slider {...newTodo.valueBind} />

Methods:

  • clear
  • onChange
  • eventBind - binds the value and onChange props to an input that has e.target.value
  • valueBind - binds the value and onChange props to an input that's using only value in onChange (like most external components)

Properties:

  • hasValue

useArray

const todos = useArray([]);

Methods:

  • push - similar to native doesn't return length tho
  • unshift - similar to native doesn't return length tho
  • pop - similar to native doesn't return element tho
  • shift - similar to native doesn't return element tho
  • clear
  • removeIndex
  • removeById - if array consists of objects with some specific id that you pass all of them will be removed
  • modifyById - if array consists of objects with some specific id that you pass these elements will be modified.
  • move - moves item from position to position shifting other elements.
    So if input is [1, 2, 3, 4, 5]

    from  | to    | expected
    3     | 0     | [4, 1, 2, 3, 5]
    -1    | 0     | [5, 1, 2, 3, 4]
    1     | -2    | [1, 3, 4, 2, 5]
    -3    | -4    | [1, 3, 2, 4, 5]

useMap

const { value, set } = useMap([['key', 'value']]);
const { value: anotherValue, remove } = useMap(new Map([['key', 'value']]));

Actions:

  • set
  • delete
  • clear
  • initialize - applies tuples or map instances
  • setValue

useSet

const set = useSet(new Set<number>([1, 2]));

useSetState

const { state, setState, resetState } = useSetState({ loading: false });
setState({ loading: true, data: [1, 2, 3] });
resetState();

Methods:

  • setState(value) - will merge the value with the current state (like this.setState works in React)
  • resetState() - will reset the current state to the value which you pass to the useSetState hook

Properties:

  • state - the current state

usePrevious

Use it to get the previous value of a prop or a state value. It's from the official React Docs. It might come out of the box in the future.

const Counter = () => {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return (
    <h1>
      Now: {count}, before: {prevCount}
    </h1>
  );
};

usePageLoad

const isPageLoaded = usePageLoad();

useScript

const { ready, error } = useScript({
  src: 'https://example.com/script.js',
  startLoading: true,
  delay: 100,
  onReady: () => {
    console.log('Ready');
  },
  onError: (error) => {
    console.log('Error loading script ', error);
  },
});

useDocumentReady

const isDocumentReady = useDocumentReady();

useGoogleAnalytics

useGoogleAnalytics({
  id: googleAnalyticsId,
  startLoading: true,
  delay: 500,
});

useWindowSize

const { width, height } = useWindowSize();

useDelay

const done = useDelay(1000);

usePersist

const tokenValue = usePersist('auth-token', 'value');

useToggleBodyClass

useToggleBodyClass(true, 'dark-mode');

useOnClick

useOnClick((event) => {
  console.log('Click event fired: ', event);
});

useOnClickOutside

// Pass ref to the element
const containerRef = useOnClickOutside(() => {
  console.log('Clicked outside container');
});

useFocus

// pass ref to the element
// call focusElement to focus the element
const [elementRef, focusElement] = useFocus();

useImage

const { imageVisible, bindToImage } = useImage(src, onLoad, onError);

Migration from v1 to v2

  • Migration to array based API is a bit more complex but recommended (especially if you're using ESLint rules for hooks). Take a look at this section in array API docs.
  • All lifecycle helpers are removed. Please replace useOnMount, useOnUnmount and useLifecycleHooks with useEffect. This:
useOnMount(() => console.log("I'm mounted!"));
useOnUnmount(() => console.log("I'm unmounted"));
// OR
useLifecycleHooks({
  onMount: () => console.log("I'm mounted!"),
  onUnmount: () => console.log("I'm unmounted!"),
});

to:

useEffect(() => {
  console.log("I'm mounted!");
  return () => console.log("I'm unmounted");
}, []);
  • bind and bindToInput are got renamed to valueBind and eventBind respectively on useInput hook

NPM DownloadsLast 30 Days