ProductPromotion
Logo

React.JS

made by https://0x3d.site

GitHub - kitze/react-hanger: A collection of useful React hooks
A collection of useful React hooks . Contribute to kitze/react-hanger development by creating an account on GitHub.
Visit Site

GitHub - kitze/react-hanger: A collection of useful React hooks

GitHub - kitze/react-hanger: A collection of useful React hooks

๐Ÿ™‹โ€โ™‚๏ธ 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

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):

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

More Resources
to explore the angular.

mail [email protected] to add your project or resources here ๐Ÿ”ฅ.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here ๐Ÿ”.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory