widehook
TypeScript icon, indicating that this package has built-in type declarations

2.0.23 • Public • Published

widehook.js

Sublime's custom image

Usage

Create hook

import { createWideHook } from 'widehook'

export const useMessage = createWideHook({
  init: 'text',
})

Use in component

const Button = () => {
  const [message, setMessage] = useMessage()

  return <button onClick={() => setMessage('One Value')}>
      {message}
  </button>
}

demo

Or even outside

const setSpecialMessage = (text: string) => {
  const [message, setMessage] = useMessage() // yes, it works here

  setMessage(text)
}

Options

on(state, setState) { }

On each "setState" define action:

export const useMessage = createWideHook({
  init: 'text',
  on(text, setText) {
    if (text === 'specific message') setText('another text')
  },
})

Access another state

Take another widehook to read and update:

export const useText = createWideHook({
  init: 'text',
  on(text, setText) {
    const [number, setNumber] = useNumber()
    if (text === 'specific text') setNumber(7)
  },
})

returnObject: true

If true - hook returns an object with named props and methods:

const useCounter = createWideHook({
  init: 3,
  returnObject: true,
  name: 'counter', // requires name
})

const { counter, setCounter } = useCounter() // in component

Types

Type declaration for init value:

type Text = 'One Text' | 'Another Text' | 'Completely Different Text'

export const useText = createWideHook({
  init: 'text' as Text,
})

Package Sidebar

Install

npm i widehook

Weekly Downloads

3

Version

2.0.23

License

MIT

Unpacked Size

37.2 kB

Total Files

12

Last publish

Collaborators

  • yorkblansh