1.0.4 • Published 4 years ago
@zanomate/use-controllable-state v1.0.4
use-controllable-state
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-stateor Yarn:
yarn add @zanomate/use-controllable-stateUsage
Import the useControllableState custom hook
import useControllableState from '@zanomate/use-controllable-state'Use inside your component; it takes 3 parameters:
- defaultValueuse to initialize your local state when your component is used as "uncontrolled".
- valueuse to control your local state when your component is used as "controlled".
- onChangecalled 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.