• Stars
    star
    1,935
  • Rank 23,945 (Top 0.5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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

More Repositories

1

JSUI

A powerful UI toolkit for managing JavaScript apps
JavaScript
4,244
star
2

awesome-conference-practices

Did you like anything in particular about a conference? Let's make an awesome list 🎉
1,050
star
3

react-genie

A set of React components for animating elements as they scroll into the viewport
TypeScript
747
star
4

twizzle-landing

The landing page for Twizzle
JavaScript
644
star
5

mobx-router

A simple router for MobX + React apps
TypeScript
509
star
6

react-electron-example

An example of using React (create-react-app) with Electron
JavaScript
349
star
7

twizzle

A desktop app for Twitter DM & composing tweets from the menubar. Works on macOS, Windows, and Linux.
JavaScript
275
star
8

styles-debugger

A helper for visually debugging styles in CSS-in-JS
JavaScript
130
star
9

copy-lite

Copy to clipboard function with no dependencies
TypeScript
119
star
10

react-tiniest-router

The tiniest router for React, built with hooks
TypeScript
105
star
11

graphql-user

Reusable utility methods for GraphQL authentication in Node.js
TypeScript
104
star
12

react-long

A LongPress component for React
JavaScript
88
star
13

voice-command-list

Temporary repository for the voice-command-list project.
88
star
14

react-disable

A React component for disabling a section of an app
TypeScript
77
star
15

react-in-markdown

Render custom React components in Markdown
JavaScript
67
star
16

gtb

Gulp The Builder
JavaScript
40
star
17

twiwdev

This Week In Webdev
27
star
18

tired-of-webdev

26
star
19

kitze-js-helpers

JS helper functions
JavaScript
25
star
20

phone-browser

Source code for why-iphone-x
JavaScript
22
star
21

mobx-router-example

MobX router example
JavaScript
20
star
22

rttr

A tiny router for mobx-state-tree apps
JavaScript
13
star
23

shortcuts-to-icloud

Watch a folder with js shortcuts for Siri and transfer them to iCloud on every change
JavaScript
13
star
24

extension-twitter-no-views

Hides the annoying view count on Twitter with CSS
Shell
12
star
25

payment-gateway-calculator

A calculator for comparing fees and profit between different payment processor gateways
JavaScript
11
star
26

react-genie-emotion

Animations for using react-genie with emotion
TypeScript
9
star
27

styled-mixins

A collection of css-in-js mixins
TypeScript
9
star
28

apollo-react-user

Opinionated package for adding authentication to a React + Apollo app
TypeScript
8
star
29

kitze-sass-helpers

Helpful sass mixins for generating BEM syntax and making SASS development easier
CSS
6
star
30

react-plop

React templates for plop
JavaScript
6
star
31

prisma2-template

TypeScript
5
star
32

snakepong-gpt-4

snakepong game made by GPT-4
JavaScript
5
star
33

react-academy-labs-starter-2

JavaScript
4
star
34

mantine-layout-components

Horizontal, Vertical, and Grid components for Mantine
TypeScript
3
star
35

fakeGPT

generate fake screenshots of conversations with chatGPT
TypeScript
3
star
36

mobx-router-landing

A landing page for mobx-router
JavaScript
3
star
37

stylz

Mixins and helpers for writing styles in JS
JavaScript
3
star
38

react-genie-styled-components

A set of animations for using react-genie with styled-components
TypeScript
3
star
39

postgres-s3-backups

TypeScript
2
star
40

hello-github-actions

2
star
41

kitze

1
star
42

react-academy-graphpack-starter

JavaScript
1
star
43

electrontest

electron
JavaScript
1
star
44

kitze-react-plopfile

My plop setup for quickly generating react components
1
star