Tutorial

Easy State Management with React Values

Published on August 26, 2018
author

joshtronic

Easy State Management with React Values

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! 💥

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
joshtronic

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.