Skip to content

Instantly share code, notes, and snippets.

@marcusradell
Last active September 21, 2017 09:46
Show Gist options
  • Save marcusradell/4e53492774b68e3d25351c7ee9296a95 to your computer and use it in GitHub Desktop.
Save marcusradell/4e53492774b68e3d25351c7ee9296a95 to your computer and use it in GitHub Desktop.
Lift state sideways!

Lift state sideways

This is a CFP for ReactiveConf Please ⭐️ this gist if you want to see me present at Reactiveconf!

All other feedback is welcome as well <3

Problem

Have you written enough states managing toggle buttons yet? Do you feel like lifting state upwards spreads out concerns and couples code?

There are so many (so so many) ways to handle state, so why pitch another way? I wish that we could agree on a way to describe how components model their state, without actually handling it.

This would mean that we could adopt different connectors in different projects while maintaining a single set of components. This would mean that reusing the same logics for different views would be really simple. And you can always change your mind later on while keeping your business logic.

Solution

This is the format I propose for components: demo input component

It simply wraps the React components in a factory function.

By extracting props from React, we can make our state management React agnostic while keeping the normal benefits in our React views.

By separating the model and view, we can easily export multiple stateless render functions and connect them to to our state management library of choice.

By adding a factory function around the render functions, we can bind actions to props outside of React and avoid rebinding on render.

A minimal React stateful connector is 17 LOCs plus its utility of 6 LOCs.

It is easy to eject from, and easy to try out and mix with ordinary React components. Once the connector is in place, you will have a single source of truth where you can make your own manager that suits your own project needs like we did with planck-state that extends the model with async capabilities and handling form submissions.

Even if you just started out with React, this talk can show you that it is possible to write highly testable and flexible components. All this without frameworks while reducing boilerplate code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment