ianstormtaylor / react-values

A set of tiny React components for handling state with render props.
https://git.io/react-values
MIT License
1.02k stars 39 forks source link

add "connected" values #30

Closed ianstormtaylor closed 5 years ago

ianstormtaylor commented 6 years ago

Right now the values are limited to being a single point in the render tree. But it's fairly common to end up needing to use the same value in two places, and have them stay in sync. This can be solved with "context", or with things like Redux, but they're all kind of overkill.

It would be cool if this library exposed factory functions for each type of value, so that you could create your own "connected" values. For example:

import { createBooleanValue } from 'react-values'

const ReadonlyValue = createBooleanValue(false)

<App>
  <Content>
    <ReadonlyValue>
      {({ value, toggle }) => (
        ...
      )}
    </ReadonlyValue>
  </Content>
  <Sidebar>
    <ReadonlyValue>
      {({ value, toggle }) => (
        ...
      )}
    </ReadonlyValue>
  </Sidebar>
</App>

It would give you a component that has the same interface as the usual <BooleanValue>-style components, but maintain its state across multiple render locations. And it would also expose the transforms as static methods, for convenience, like ReadonlyValue.toggle().

Pretty sure this would eliminate like 90% of the use cases people end up "needing" to move to a global store like Redux/Mobx for.

cdock1029 commented 5 years ago

https://gist.github.com/cdock1029/fe1a88db5972b62bc67d2a255266b5f7