• Stars
    star
    540
  • Rank 82,257 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 3 years ago

Reviews

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

Repository Details

A set of reusable React Hooks.

React Hooks Lib Β· Build Status Coverage Status

A set of reusable React Hooks.

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Installation

npm i react-hooks-lib --save

Examples

Visit storybook

Hooks

Name Arguments Returns
Lifecycles
useDidMount f -
useWillUnmount f -
useDidUpdate f, conditions -
State
createContextState initial { ContextProvider, ContextConsumer, set, useSelector, useSet }
createGlobalState initial { GlobalProvider, GlobalConsumer, set, useSelector, useSet }
useMergeState initial { state, set }
useNestedState initial { state, get, set }
useBind Please visit storybook Please visit storybook
useNestedBind Please visit storybook Please visit storybook
useStateCallback initial, f { state, set }
useUndo initial { past, present, future, set, undo, redo }
useCounter initial { count, set, reset, inc, dec }
useToggle initial { on, set, reset, toggle }
useList initial { list, set, reset, push, sort, filter }
useMap initial { values, set, reset, clear, get, has, del }
Effect
useShallowEqualEffect f, deps -
useDeepEqualEffect f, deps -
Network
useFetch initialUrl, initialOptions, config { loading, data, error, fetch, setUrl, setOptions, setData }
useOnlineStatus
Feedback
useHover - { hovered, bind }
useActive - { active, bind }
useFocus - { focused, bind }
useTouch - { touched, bind }
Data Entry
useField initial { value, set, reset, bind }
Async
useAsync f { f, loading }

API

useDidMount(f)

Similar to componentDidMount in React class component.

Arguments

  • f: () => void: f is called when component did mount.
import { useDidMount } from 'react-hooks-lib'

const MyComponent = () => {
  useDidMount(() => {
    console.log('didMount')
  })
}

useWillUnmount(f)

Close to the componentWillUnmount in React class component.

Arguments

  • f: () => void: f is called when component will unmount.
import { useWillUnmount } from 'react-hooks-lib'

const MyComponent = () => {
  useWillUnmount(() => {
    console.log('willUnmount')
  })
}

useDidUpdate(f, options?)

Similar to componentDidUpdate, it only runs on updates.

Arguments

  • f: () => Function | void: f is called on every updates. Like useEffect, f can return a clean-up function.
  • conditions?: Array<any>: Optional array for conditionally firing an effect, same as the second argument passed to useEffect.
import { useDidUpdate, useCounter } from 'react-hooks-lib'

const MyComponent = () => {
  const { count, inc } = useCounter(0)
  useDidUpdate(() => {
    console.log('DidUpdate')
  })
  return (
    <div>
      {`count: ${count}`}
      <button onClick={() => inc(1)}>+1</button>
    </div>
  )
}

createContextState(initial?)

createGlobalState(initial?)

useMergeState(initial?)

Arguments

  • initial?: Object: Initial state object, default is {}.

Returns

  • state: Object: Current state object.
  • set: ((Object) => Object) | Object: Like setState in React class component, merge the old and new state together.
import { useMergeState } from 'react-hooks-lib'

const MergeState = () => {
  const { state, set } = useMergeState({ name: 'Victor', age: 1 })
  return (
    <div>
      <h3>useMergeState</h3>
      <div>
        {`state: ${JSON.stringify(state)}`}
        <button onClick={() => set(({ age }) => ({ age: age + 1 }))}>age+1</button>
      </div>
    </div>
  )
}

useNestedState

Arguments

  • initial?: Initial state, default is undefined.

Returns

  • state: Current state.
  • get(pathString, defaultValue): Get value form state at a specific pathString. eg: get("a.b.c")/get("" | undefined), if pathString is empty,it will return the state object.
  • set: (pathString, newValue | prevValue => newValue): Set value at a specific pathString. eg: set("a.b.c", prev => prev + 1)/set("" | undefined, {}). if pathString is empty,it will set the entire state object.

useStateCallback(initial, f?)

useUndo(initial)

useCounter(initial)

import { useCounter } from 'react-hooks-lib'

const Counter = () => {
  const {
    count, inc, dec, reset,
  } = useCounter(1)
  return (
    <div>
      {count}
      <button onClick={() => inc(1)}>+1</button>
      <button onClick={() => dec(1)}>-1</button>
      <button onClick={reset}>reset</button>
    </div>
  )
}

useToggle(initial)

import { useToggle } from 'react-hooks-lib'

const Toggle = () => {
  const { on, toggle, reset } = useToggle(false)
  return (
    <div>
      {String(on)}
      <button onClick={toggle}>toggle</button>
      <button onClick={reset}>reset</button>
    </div>
  )
}

useList(initial)

import { useList } from 'react-hooks-lib'
const List = () => {
  const { list, sort, filter } = useList([1, 4, 2, 3, 4, 2, 6, 8, 3, 4])
  return (
    <div>
      list:
      {JSON.stringify(list)}
      <button onClick={() => sort((x, y) => x - y)}>sort</button>
      <button onClick={() => filter(x => x >= 4)}> greater than or equal to 4</button>
    </div>
  )
}

useMap(initial)

useFetch(initialUrl, initialOptions?, onMount?)

import { useField, useFetch } from 'react-hooks-lib'

const Fetch = () => {
  const getUrl = text => `https://api.github.com/search/repositories?q=${text}`
  const { value, bind } = useField('react')
  const { data, loading, setUrl } = useFetch(getUrl('react'))
  return (
    <div>
      <h3>useFetch</h3>
      <input type="text" value={value} {...bind} />
      <button onClick={() => {
        setUrl(getUrl(value))
      }}
      >
        search
      </button>
      {
        loading
          ? <div>Loading...</div>
          : (<span>{`total_count: ${data.total_count}`}</span>)
      }
    </div>
  )
}

useOnlineStatus()

useHover()

import { useHover } from 'react-hooks-lib'

const Hover = () => {
  const { hovered, bind } = useHover()
  return (
    <div>
      <div {...bind}>
        hovered:
        {String(hovered)}
      </div>
    </div>
  )
}

useActive()

useFocus()

useTouch()

useField(initial)

  import {useField} from 'react-hooks-lib'

  const Input = () => {
    const { value, bind } = useField('Type Here...')

    return (
      <div>
        input text:
        {value}
        <input type="text" {...bind} />
      </div>
    )
  }

  const Select = () => {
    const { value, bind } = useField('apple')
    return (
      <div>
        selected:
        {value}
        <select {...bind}>
          <option value="apple">apple</option>
          <option value="orange">orange</option>
        </select>
      </div>
    )
  }

More Repositories

1

rough-charts

πŸ“ˆ A responsive, composable react charting library with a hand-drawn style.
TypeScript
1,516
star
2

weird-fonts

𝑨 π‘±π’‚π’—π’‚π‘Ίπ’„π’“π’Šπ’‘π’• π’‘π’‚π’„π’Œπ’‚π’ˆπ’† 𝒕𝒉𝒂𝒕 𝒕𝒖𝒓𝒏 π’‚π’π’‘π’‰π’‚π’π’–π’Žπ’†π’“π’Šπ’„ 𝒄𝒉𝒂𝒓𝒂𝒄𝒕𝒆𝒓𝒔 π’Šπ’π’•π’ π’˜π’†π’Šπ’“π’… 𝒇𝒐𝒏𝒕 π’”π’•π’šπ’π’†.
TypeScript
609
star
3

vue-hooks-form

Building forms with vue composition API.
TypeScript
141
star
4

leetcode-site-generator

Generate your personal LeetCode website with one command!
JavaScript
103
star
5

reactablejs

A react high-order component for interact.js(drag and drop, resizing and multi-touch gestures).
TypeScript
62
star
6

react-multi-crops

A multiple cropping component for React
JavaScript
40
star
7

reason-hooks-lib

A set of reusable ReasonReact hooks.
Reason
32
star
8

reason-hooks-testing-library

ReasonML bindings for react-hooks-testing-library
Reason
25
star
9

reason-unstated

A simple reason react state management library that help you share hook state and logic easily.
OCaml
15
star
10

chrome-extension-starter-kit

Chrome Extension Starter Kit
JavaScript
13
star
11

reason-powerplug

πŸ”Œ Renderless Containers For ReasonReact
OCaml
11
star
12

nqm

npm with query
JavaScript
8
star
13

hooks-to-others

Transform react hooks into render props and high-order component patterns.
TypeScript
4
star
14

bookmark-search

A Chrome extension for searching bookmark quickly.
JavaScript
4
star
15

mac-look-up-log

Look up workflow for macOS
3
star
16

redux-and-react-redux

Simple Redux and React Redux implementation
JavaScript
3
star
17

js-lens

Safely accessing and updating nested object with functional features.
TypeScript
3
star
18

vue-reactivity

JavaScript
2
star
19

fusuma-imgs

1
star
20

mini-context-store

A react state management library using new context api
JavaScript
1
star
21

leetcode-solutions

Victor's LeetCode Website.
JavaScript
1
star
22

gatsby-starter-gcn

JavaScript
1
star
23

ant-design-snippets

An ant design snippets extension for VS Code.
1
star
24

safety-redux

Query and mutate Redux state safely.
JavaScript
1
star
25

beizhedenglong.github.io

beizhedenglong.github.io
HTML
1
star
26

rc-value

Make React component switch between Controlled Component and Uncontrolled Component easily.
JavaScript
1
star