Skip to content

Instantly share code, notes, and snippets.

@johno
Last active October 13, 2016 18:40
Show Gist options
  • Save johno/98a9fee76ca1e13cef7ac4bcb3e34d40 to your computer and use it in GitHub Desktop.
Save johno/98a9fee76ca1e13cef7ac4bcb3e34d40 to your computer and use it in GitHub Desktop.
[Thinking Out Loud] Functional, unidirectional state management for React based on redux

↻ rehoc

Work in progress

Functional, unidirectional state management for React based on redux.

Why?

redux is great for predictably handling state but doesn't leverage Higher Order Components out of the box. rehoc provides functional, HOCs that can be used to cleanly "connect" your containers to state and action dispatchers. Unlike redux, actions are asynchronous by default and live within your container.

Installation

npm i -S rehoc

Usage

The below snippet is by no means functional, but might looks something similar to a desirable API.

import React, { Component } from 'react'
import rehoc, { send } from 'rehoc'

class Todos extends Component {
  retrieveTodos = () => {
    fetch('/the/data')
      .then(res => send('todos:updateAll', { list: res.body }))
  }

  deleteTodo = (id) => {
    fetch(`/delete/the/todo/${id}`, { headers, method })
      .then(res => send('todos:delete', { id }))
  }

  render () {
    const { todos } = this.state

    return <ul children={todos.map(t => <TodoItem {...t} deleteTodo={this.deleteTodo} />)} />
  }
}

const TodoItem = rehoc(({ id, text, deleteTodo }, send /*, state */) => (
  <li>
    {text}
    <a onClick={() => deleteTodo(id)} children='x' />
  </li>
))

export default rehoc(Todos, 'todos')

In this contrived example, Todos serves as the container element. It contains the todos state that is likewise namespaced. The rehoc enhancement that occurs exposes three additional properties, todos, send, and state. todos is the state contained within the todos namespace of the global state. send is the dispatcher for actions and reducers. state is the global application state, it's read only.

The TodoItem is a pure, functional component. It's enhanced by the rehoc component which exposes additional arguments (send and state). send can be used to dispatch actions, and state contains the global application state. It's recommended to explicitly pass in data as props to functional components, but rehoc exposes it if needed [THIS SHOULD NOW ONLY BE PASSED IN TO THE CONTAINER COMPONENTS].

What about middleware?

rehoc will also expose a middleware hook that can be used for logging, state tracking, etc.

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