Easy State Management with React Values

joshtronic

It happens to the best of us. We start a new project with the best intentions of writing clean and maintainable code. Fast forward a month or two into the project and we’ve implemented the same boolean toggle state in twenty different places. Things go further off the rails if multiple developers have implemented the same state logic in different ways. Fortunately, react-values is here to save the day!

react-values is a set of composable React components that makes it easy to manage component state with render props. You can quickly add in state management for a single value, toggle booleans, increment/decrement numbers and even manage more complex data structures like an object!

One of the goal’s of the react-values project is to follow familiar conventions, both in React as well as JavaScript. A great example of this is the ArrayValue component which provides methods like push and pop.

You’re not limited to state management in a singular scope either, with react-values connected components, you can create a value that can be used multiple times inside of your component or even across your app.

Do you have a scenario where you’d prefer to use a controlled component instead of an uncontrolled component? Simply pass your react-values component a value or defaultValue and you’re good to go.

Getting Started

Ready to start playing around with react-values?

Great! We’re going to get started by installing the react-values dependency via npm:

$ npm install --save react-values

or via yarn:

$ yarn add react-values

Then include react-values in your code where you’d like to use it:

import ReactValues from "react-values";

Or if you don’t need everything, you can import the individual values:

import { BooleanValue } from "react-values";

Basic State Management

When it comes to state management in components, there are two things I know I’ve personally implemented at least hundred or so times. The first is the storage of a string that was input by the user.

react-values comes with a StringValue component that eliminates all of the necessary boilerplate (setting up the initial state, writing an on change handler, et cetera) necessary to store a string in the state:

<StringValue>
  {({ value, set }) => (
    <input type="text" onChange={e => set(e.target.value)} />
  )}
</StringValue>

The other major offender would be the boolean toggle. Regardless if you go with a simple check box, or a fancy slider the underpinnings tend to be the same; establish the initial state and then write an on change handler.

Similar to StringValue we can use BooleanValue and get things cookin’:

<BooleanValue>
  {({ value, toggle }) => (
    <input type="checkbox" onClick={toggle} checked={value} />
  )}
</BooleanValue>

Observing State Changes

The previous examples are great if you only need to track the state in the component itself, but what if we need to know when the state has changed and/or send it back to a server for storage?

In those scenarios, we can simply include an onChange property on our react-values component (all of them support this) and we can handle the state changes as we see fit:

<StringValue onChange={v => console.log(v)}>
  {({ value, set }) => (
    <input type="text" onChange={e => set(e.target.value)} />
  )}
</StringValue>

In this example I’m logging the new value out to the console, but you can easily replace that with an AJAX call or some other logic to satisfy your needs.

Using a State Value Multiple Times

I mentioned earlier that sometimes you need to use a state value multiple times in different places in your code. These scenarios usually result in introducing a heavier weight statement management library like React Redux into the mix.

If you’ve ever used react-redux you know that sometimes it’s just too much and that it can introduce a new layer of complexity that you may want to avoid. If that’s the case, you can use react-values connected values to create a component you can reuse when you want to keep the state in sync:

import { createBooleanValue } from "react-values";

const ConnectedBooleanValue = createBooleanValue();

// ...

This new ConnectedBooleanValue can be used and reused as if it were an instance of BooleanValue, allowing you to share this state anywhere in your app.

Similar to the onChange handler, every value type in react-values has an equivalent create method.

Conclusion

I hope you found this post about react-value informative and that your future coding adventures include significantly less state management boilerplate logic.

If you’d like to see the examples from this article in action, you can check them out over on CodeSandbox.

Enjoy! 💥

  Tweet It

🕵 Search Results

🔎 Searching...