bitten
bitten

Reputation: 2543

ReactJS and separate model

I'm looking at ReactJS as being the view in my application which has a model and a bunch of components. I can see how my model can talk to React, but how does React then talk to the rest of my application?

It's very simple to pass in data or a model into React:

var ui = ReactDOM.render(<UI model={model} />, document.getElementById('ui'));

I assumed you could set the model like so:

constructor(props) {
  super(props); 
  this.state = {
    model: this.props.model
  }
}

Although state should treated as immutable according to the documents, as it's not updated instantly. So I cannot access my model through state, I have a very bad codepen example here showing how I've made it work in the wrong way. How else can I do this?

Upvotes: 4

Views: 2846

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42480

There are literally hundreds of ways to connect your React view layer with an underlying model. React itself is completely implementation agnostic when it comes to models.


However, there are some interesting approaches to this problem that have proven themselves.

One of them is Facebook's Flux pattern. It is based on the idea of data stores that are kept separately from the React components without a direct dependency on them. Instead, changes to your model data are made by dispatching actions (e.g. user logged on, filter was applied), which can be thought of like events. Those actions are then dispatched by a central dispatcher to the different stores.

Each of the stores holds a different part of the state of your application and continuously updates it according to the dispatched actions. Your React components can now pick and choose the parts of the state that they require to be rendered and subscribe to changes to this particular part of the application state.

Flux pattern
(source: github.io)

By applying this pattern, you can keep the dependencies between the React components, which render your user interface as a function of the application's state and the stores, which represent your application's model and contain all the business logic.

This ensures both that the parts of your application stay reusable and replaceable and also that the state of your application is always consistent.


Note however that, as mentioned above, this is only one possible approach amongst many. It may be a good entry point though to understand the value behind the unidirectional dataflow and immutable data structures that make this pattern so powerful.

Upvotes: 6

Related Questions