@zanomate/use-controllable-state
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

use-controllable-state

npm (scoped) npm type definitions npm peer dependency version (scoped)

A React custom hook to manage double controlled/uncontrolled behaviors.

Useful for creating custom Input components.

const MyCustomInput = ({ defaultValue, value, onChange }) => {
  
  // This takes parameters passed from outside as props.
  const [state, setState] = useControllableState(
    defaultValue,
    value,
    onChange
  )
  
  const handleChange = (e) => {
    // Here I can transform the value back for the local state.
    setState(e.target.value)
  }

  // Here I can add my custom behavior to the local state.
  return (
    <input
      value={state}
      onChange={handleChange}
    />
  )
}

Install

Install via NPM:

npm i @zanomate/use-controllable-state

or Yarn:

yarn add @zanomate/use-controllable-state

Usage

Import the useControllableState custom hook

import useControllableState from '@zanomate/use-controllable-state'

Use inside your component; it takes 3 parameters:

  • defaultValue use to initialize your local state when your component is used as "uncontrolled".
  • value use to control your local state when your component is used as "controlled".
  • onChange called each time the state is updated (for both "controlled" and "uncontrolled" behaviors).
const [state, setState] = useControllableState(
  defaultValue,
  value,
  onChange
)

Returns an array with a state and its setter, as like the React useState.

Readme

Keywords

none

Package Sidebar

Install

npm i @zanomate/use-controllable-state

Weekly Downloads

1

Version

1.0.4

License

ISC

Unpacked Size

4.22 kB

Total Files

7

Last publish

Collaborators

  • matteozanoncello