How to create temporary States in ReactRedux?

I'm assuming by "values of every reducer" you are referring to the entire app state.

You can certainly slice up your state and expose only the necessary pieces to specific components. That is what the connect method from the react-redux bindings is for. connect takes a function (e.g. mapStateToProps) which in turn takes your entire app state and exposes only the pieces you designate as props to the component you are "connecting" to redux.

For example, suppose you have a simple React component like this that shows a user's name and address:

var myComponent = React.createClass({
  render: function() {
    return (
      <div>{Name from redux state goes here}</div>
      <div>{Address from redux state goes here}</div>
    );
  }
});

Obviously you don't need to send your entire app state to this component, just the piece with the user's name and address. So you use connect like so:

// the "state" param is your entire app state object.  
function mapStateToProps(state) {
  return {
    name: state.name,
    address: state.address
  }
}

var connectedComponent = connect(mapStateToProps)(myComponent);

The wrapped myComponent now effectively looks like this:

var myComponent = React.createClass({
  propTypes: {
   name: React.PropTypes.string // injected by connect
   address: React.PropTypes.string // injected by connect  
  },

  render: function() {
    return (
      <div>{this.props.name}</div>
      <div>{this.props.address}</div>
    );
  }
});

According to the Redux docs:

The state of your whole application is stored in an object tree within a single store.

One state. One store. That's it. You can create local states in your individual components that are informed by the larger application state, but at that point you're just copying parts of the larger state that already exist.

Keep in mind that in a complex app, you will not make the entire state available to your "smart" components. Even if you have 100 reducer functions, when you connect a component to the store, you can use mapStateToProps to pick only the parts of the application state you want, and create props for your component from those. So you would never see all of the parts of the state that you don't use, even if you know in the back of your mind that they exist.

This is really a great architectural pattern. With one state you have a single source of truth. It is impossible for any part of your app to have stale data because of this. Remember that you are only defining your state structure when you initialize your application state, and not loading all data. Therefore, there is no performance hit by initializing the whole structure at the start. And again, you will never be loading the entirety of your application state into a single component anyway (unless it requires that) so your props will always be manageable.

Tags:

Reactjs

Redux