Coder Social home page Coder Social logo

react-rx-component's Introduction

react-rx-component

DEPRECATED

This project has been superseded by rx-recompose.

build status npm version

Yet another RxJS library for React :)

Create smart components — also known as container components — using RxJS observables.

npm install --save react-rx-component rx

Don't setState() — transform props

React is all about state management. One of the biggest traps new React developers fall into is an over-reliance on setState() to construct big, complicated state machines. Components like that are fragile, error-prone, and fail to take full advantage of React's powerful data flow model. Instead, it's best to minimize local component state and use derived data, in the form of props, wherever possible.

A common strategy is to separate your app into smart and dumb components. Smart components take care of state management, subscriptions, and other messy stuff, then pass props along to its children. The children are dumb components, which have no state, and merely return elements for given props.

react-rx-component lets you create "stateful" smart components without ever using setState().

Using the RxJS library, transform an observable sequence of props received from the owner into a sequence of props to be passed to children. This is the essence of what all smart components do — take some props from the owner, combine it with some local state, and sanitize the result by passing it down as nice, clean props.

To illustrate, let's compare how to create a simple counter the normal way and with react-rx-component.

First, the normal way. We'll follow best practices by separating our counter into smart and dumb components:

class CounterContainer extends React.Component {
  state = { count: 0 }

  handleIncrement = () => {
    this.setState(state => ({
      count: state.count + 1
    }));
  }

  render() {
    return (
      <Counter
        {...this.props}
        count={this.state.count}
        increment={this.handleIncrement} />
    );
  }
}

class Counter extends React.Component {
  render() {
    return (
      <div>
        {props.count}
        <button onClick={increment}>+</button>
      </div>
    );
  }
}

And now let's implement this same functionality with react-rx-component. Inline comments show how certain parts correspond to the normal version:

const CounterContainer = createRxComponent(props$ => {
  const increment$ = funcSubject(); // handleIncrement
  const count$ = increment$
    .startWith(0) // state = { count: 0 }
    .scan(count => count + 1); // this.setState((state) => ({ count: count + 1 }))

  return Observable.combineLatest(props$, count$, (props, count) => ({
    ...props,
    increment: increment$,
    count
  }));
}, Counter);

// In a future version of React, pure functions like this are valid components
// https://github.com/facebook/react/pull/3995
function Counter(props) {
  const { count, increment, ...rest } = props;
  return (
    <div {...rest}>
      {props.count}
      <button onClick={increment}>+</button>
    </div>
  );
}

funcSubject() is a neat trick borrowed from rx-react. It creates an observable sequence that can be used like a callback function. The value sent to the function is added to the sequence. Here, we're using it as a click handler.

As you can see, the entirety of React's state API can be expressed in terms of observable operators.

  • Instead of setState(), create a new observable sequence and combine.
  • Instead of getIntialState(), use startWith().
  • Instead of shouldComponentUpdate(), use distinctUntilChanged().

Other benefits include:

  • Instead of getDefaultProps(), use startWith().
  • No distinction between state and props — everything is simply an observable.
  • No need to worry about unsubscribing from event listeners.
  • Sideways data loading is trivial.
  • Access to the full ecosystem of RxJS libraries.
  • Free performance optimization – safely implements shouldPureComponentUpdate() from react-pure-render.
  • It's more fun.

API

import { createRxComponent, funcSubject } from 'react-rx-component';

createRxComponent(mapProps)

createRxComponent(mapProps, render)

createRxComponent(mapProps, Component)

Creates a React Component or a higher-order component. Use this instead of React.createClass() or extending React.Component.

mapProps() is a function that maps an observable sequence of props to a sequence of child props, like so:

props$ => childProps$

NOTE mapProps() also receives a sequence of contexts as the second parameter.

createRxComponent() can be passed a render function or a React component. A render function is a function that maps child props to a React element:

props => vdom

Passing a React component is effectively the same as passing a render function that looks like this:

props => <Component {...props} />

The resulting component is a subclass of React.Component, so you can set propTypes and contextTypes like normal.

Alternatively, you can choose to omit the second parameter. In this case, a higher-order component is returned instead of a normal React component. E.g.

const higherOrderComponent = createRxComponent(mapProps);

class MyComponent extends React.Component {...}

export default higherOrderComponent(MyComponent);

You can also use it as a decorator:

@createRxComponent(mapProps)
export default class MyComponent extends React.Component {...}

Why the extra step? Why not return a sequence of vdom?

You may be wondering why we don't just combine the two steps and map directly from a sequence of props to a sequence of React elements. Internally, the separation allows us to prevent unnecessary renders using shouldComponentUpdate(). If the same set of props are broadcast multiple times, there are no extra renders.

funcSubject()

Creates an RxJS Subject that can be used like a callback function. It broadcasts the value of whatever it's called with. This is very handy for creating observable sequences from event handlers, like onClick() or onChange(). See the counter example above.

The idea for this function is borrowed from rx-react by @fdecampredon.

Comparison to other libraries

  • Cycle — Cycle is a React-like, fully reactive library with a hard dependency on RxJS. I don't have much experience with Cycle, but what I do know is all very positive and exciting. The biggest downside for me is that it's not React :) The goal of this library is to incorporate reactive concepts without breaking compatibility with the larger React ecosystem.
  • cycle-react — A port of Cycle's API to React.
  • rx-react — A collection of mixins and helpers for working with React and RxJS. Rather than using mixins, react-rx-component focuses on helping you create entire components using only observables and pure functions. As mentioned above, funcSubject() is borrowed from this library.

react-rx-component's People

Contributors

acdlite avatar cesarandreu avatar xgrommx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-rx-component's Issues

ReplaySubject prototype

Hey, this is great! I was curious about this idea and mocked an eerily similar API until I found this!

I was curious about making Rx-based components that are hot-reloadable similar to redux, and maybe creating something very similar to redux using only Rx. I'm seeing similarities in composition that Rx streams could achieve? Rx streams might also be able to encapsulate local/global state pretty well, maybe even let you fork application state?

I read through some Cycle.js docs and model-view-intent streams seemed like a similar solution to Flux. I guess it feels like swapping terminology right now, I dunno.

How do we reduce with hotswapping?

Instead of sending everything through a dispatcher, I gave ReplaySubject a shot. ReplaySubject is like BehaviorSubject, but keeps everything in the stream available for consumption in the future. So if something depends on a ReplaySubject and you change the initial value (or make decrement remove 10 instead of 1), that reduce/scan will occur over the entire subject's history.

Also, I made a StreamProvider component since I figured redux hotreloading works by injecting props.

Example

I prototyped this in react-heatpack: https://gist.github.com/pstoica/c081d04d5fd1b103d6f0

Load it up by pointing to index.js. Try clicking the +/- buttons and then changing the count$ stream.

This is a little goofy right now as I'm not sure where this potential API could go and what problems I should solve (removing singletons, do we need a central dispatcher for complete undo/redo, etc). But, here's an experiment! Let me know what you think.

"setState" on componentDidMount

Hi
I'm trying to create a smart component to retrieve window size and pass it as props to the dumb component. It works fine when I resize the window.
I was wondering how i could update width and height on componentDidMount with this approach.

const TestContainer = createRxComponent(props$ => {

  const resize$ = Observable
    .fromEvent(window, 'resize')
    .map( e => ({ width: window.innerWidth, height: window.innerHeight }) )
    .startWith({ width: 0, height: 0 })

  return Observable.combineLatest(props$, resize$, (props, { width, height }) => ({
    ...props,
    width,
    height
  }))

}, Test)


function Test(props){
  const { width, height } = props
  return (
    <div>
      <p>width: {width}</p>
      <p>height: {height}</p>
    </div>
  )
} 

Rx as an event membrane

Glad to see greater Rx usage with React. I do not know Rx very well but had looked at the API and decided that it would work well with my idea of flux in my app, which is entirely event driven. Essentially, I just want to capture all input events in React components and forward them to a central hub object. I call this hub the interactor and the thin event capture layer the membrane.

The idea is to process the captured event streams further in the interacter and then have actions/tools receive the events and handle them in their own unique way. What action receives the Rx stream/s is determined by what action happens to be activated. Actions would be transitioned to by another universal picker handler that sets what action is active. Actions then ultimately modify state, which would trigger the re-render of any components listening for such state, bringing the flux flow full circle.

I was thinking this would allow my myriad actions to be abstracted from components and move toward being plugins. Would the react-rx-component be useful for this scenario or is there some other React Rx library that is better suited?

test for null in render

[react beginner here]
running the example at https://github.com/acdlite/redux-rx (TodoConnector), noticed that the render function gets called with props=null.
modifying createRxComponent to avoid that:

render() {
  const childProps = this.state;
  const { children } = this.props;

  // avoids rendering the dumb component if childProps is null
  if (!childProps) return null;

  if (typeof render === 'function') {
    return render(childProps);
  }

  if (typeof children === 'function') {
    return children(childProps);
  }
}

Ref as an observable

This came up today trying to pass a funcSubject as a ref callback function. Because we're not actually subscribed when the ref callback fires (ie before componentDidMount), the value is just kind of lost.

Using a BehaviorSubject instead fixed the issue, but I thought I'd mention it for anyone else who ran into it.

Also I was wondering why you subscribe in componentDidMount and not the constructor? It seems like it potentially adds some unnecessary work. I imagine it's a "universal" thing but I don't have any experience with that...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.