VB_
VB_

Reputation: 45692

Flux + React: when to keep state of visual components at store

Sometimes it's not obvious: where I should keep state of React view, i.e. active tab, selected option, toggler value, is input validated flag?

Actually there are two options:

  1. Throw an action and keep that data in store
  2. Keep that data as view's state

Which of them is better? Are stores intended only for data from server?


My considerations:

  1. That's bad to keep that data in store, because that lead to chain of actions. Example: you need to download data on tab selection - so you trigger an action NEW_TAB_SELECTED and from the store which handle it trigger a new action DOWLOAD_TAB_DATA.
  2. Keeping data in view allow to avoid the first action (NEW_TAB_SELECTED) and avoid action chains. But how to keep selected tab if I want to leave this view?

Upvotes: 4

Views: 289

Answers (1)

Josh
Josh

Reputation: 3475

Things that should be kept in the component's state are things which only affect that component.

So, for example, if you have a component which opens to reveal more content then the isOpen flag can be kept in state because it's internal to the component.

If the information is not part of the component (such as the text of a message and whether the message has been read) then it should be kept in a store and circulated through the app as needed.

Changing the state of a component will cause it to redraw, so try to keep state to the minimal possible representation of its state, and only store those properties in this.state.

Therefore, from what I can gather from your question, I'd suggest keeping active tab, selected option, toggler value and whether the input is validated in this.state. They are all properties of the component but don't affect any other components. I'd keep the data which populates the views in a store. I'd keep the flags which indicate the state of the view in this.state.

Hope that helps.

Upvotes: 4

Related Questions