This package has been deprecated

Author message:

This package was renamed to `use-optional-state`, please use the new package instead: https://www.npmjs.com/package/use-optional-state

use-optionally-controlled-state
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

use-optionally-controlled-state

Stable release

A React hook to enable a component state to either be controlled or uncontrolled.

The problem

Controlled components are a concept mostly known from form elements. They allow the owner to specify exactly what a component should render and to execute custom logic when the component calls a change handler.

In contrast to this, there are uncontrolled components which handle the state internally.

The tradeoff comes down to controlled components being more flexible in their usage but uncontrolled components being easier to use if the owner is not concerned with the state. Sometimes it's desireable for an owner at least configure an initial value and to potentially reset the child state later with a key.

When implementing a component, it's sometimes hard to choose one or the other since there are valid use cases for both approaches.

This solution

This hook helps you to support both patterns in your components, increasing flexibility while also ensuring ease of use.

Since the solution can be applied on a per-prop basis, you can even enable this behaviour for multiple props that are orthogonal (e.g. a <Prompt isOpen inputValue="" /> component).

Example

Implementation:

import useOptionallyControlledState from 'use-optionally-controlled-state';

function Expander({
  expanded: controlledExpanded,
  initialExpanded = false,
  onChange
}) {
  const [expanded, setExpanded] = useOptionallyControlledState({
    controlledValue: controlledExpanded,
    initialValue: initialExpanded,
    onChange
  });

  function onToggle() {
    setExpanded(!expanded);
  }

  return (
    <>
      <button onClick={onToggle} type="button">
        Toggle
      </button>
      {expanded && <div>{children}</div>}
    </>
  );
}

Usage:

// Controlled
<Expander expanded={expanded} onChange={onExpandedChange} />

// Uncontrolled using the default value for the `initialExpanded` prop
<Expander />

// Uncontrolled, but with a change handler if the owner wants to be notified
<Expander initialExpanded onChange={onExpandedChange} />

Readme

Keywords

none

Package Sidebar

Install

npm i use-optionally-controlled-state

Weekly Downloads

97

Version

1.2.0

License

MIT

Unpacked Size

17.5 kB

Total Files

12

Last publish

Collaborators

  • amann