Redux in One

R. Mark Volkmann, Object Computing, Inc.

Redux is a library for managing web application state. It is frequently used with React, but can be used with other web frameworks/libraries.

I love Redux! However, it does have a bit of a learning curve and is overkill for small to medium sized web applications. To use it one must learn about action types, action objects, action creators, dispatch, and reducers. Often other libraries are added to the mix such as react-redux, react-thunk, redux-epic, redux-saga, and redux-logic.

One of the beautiful things about React is its simplicity. Adding in all this complexity for state management spoils that, especially for beginners. But there is a much simpler approach that maintains some of the spirit of Redux without the complexity.

Before I describe it, allow me to make some statements, some of which might be controversial.

  1. If there will only ever be one of a thing in a program and you can trust the developers not to do something unintended with it, it's okay to put it in a global variable.
  2. An alternative to polluting the global namespace is to attach a value to an object that all users of the value can access.
  3. In a React application, the React object is available to all code that cares about state.
  4. Tradeoffs are worthwhile in some cases.
  5. If you don't like these tradeoffs, please use Redux.

Okay, with all of that out of the way it's time to present an alternative to Redux. Ready? Here it is!

      React.setState = this.setState.bind(this);

That's it. Done!

You can read about the setState method here.

Do this in the constructor of the topmost component. Call this from any component that needs to modify state. Every time this is called, the one state object used throughout the app (like the one store used in Redux) is updated. This assumes you will pass all data needed by components to them through props. Then the entire UI is rerendered, so any components that rely on the state change will get it. Of course this is fast due to the virtual DOM. In cases where it is not fast enough, components can implement componentShouldUpdate to improve performance.

I'm very interested in feedback on this idea. Please email me here.