react-scoped-value

1.0.3 • Public • Published

react-scoped-value

A simple way to pass and update partial context values.

Demo

A parent component can use a complex state...

function App() {
  const [state, setState] = useState({
    firstName: '',
    lastName: ''
  })

  return (
    <Scope value={state} setValue={setState}>
      <Input name="firstName" label="First Name" />
      <Input name="lastName" label="Last Name" />
    </Scope>
  )
}

...while a child component can read and update only the data it cares about.

function Input({ name, label }) {
  const [value, setValue] = useScopedValue(x => x[name])

  return (
    <label>
      {label}
      <input name={name} value={value} onChange={e => setValue(e.target.value)} />
    </label>
  )
}

When the scoped setter receives updates, it generates a fresh, immutable-safe complete state with updates applied before emitting the final object back to Scope.

/react-scoped-value/

    Package Sidebar

    Install

    npm i react-scoped-value

    Weekly Downloads

    1

    Version

    1.0.3

    License

    MIT

    Unpacked Size

    8.34 kB

    Total Files

    5

    Last publish

    Collaborators

    • dowhileluke