Flux: should not-top-level views be "dump" (do not fetch data from stores)

- 1 answer

Ad

Maybe at official flux website I saw a video were mentor said something like:

Only top-level React views should know about stores. All not top level views should be dump and receive all information as properties.

Question:Is that right? Your argumentation, please

BUT, suppose you have some small React view Button.react that's reused on multiple pages. And suppose Button.react must know about some store data. If we won't fetch all data directly from the Button.react, we get a duplication of code at each top-level component which reuse Button.react. Is that ok for you?

Ad

Answer

Ad

I hope I am understanding your question.

One of the characteristics of React is its one-way data flow. Each component can be used by another component, just like one function can call another function. Just like a function, a React component should typically be able to get all the info it needs to do work (render itself) from the arguments passed into it. This is the function of props in React. When using Flux, sometimes the React Components, which are typically near the top of the view hierarchy, that actually fetch the data from the stores to pass down thru the application are called Controller-Views.

It is not an enforceable rule that every component doesn't become a Controller-View, getting its own state directly from a store, but it is a general practice for good reason. consider the two functions:

function renderToggleButton( isSelected ){
  //... render the button
}

vs

function renderToggleButton(){
  var isSelected = StateStore.getButtonSelectedState( id );
  //... render the button
}

I think you will agree that the second function is more complicated and difficult to test. It has to know from where it is getting it's initial conditions. It also has to know how to identify itself in the context of the application. These are two things the function should not have to know.

Now imagine an application full of functions like this. If one function is misbehaving, it becomes very difficult to trace its inputs; to test it under controlled conditions. I hope that clarifies the guidance given for passing data thru the application as props.

Ad
source: stackoverflow.com
Ad