Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux vs this.state in react native

I've worked with redux for a bit after finding the mini lecture series on egghead.io. I'm trying to understand the difference between redux and this.state and when it's appropriate to use which.

Prior to redux, I set up one global container component which carried the state for the whole app. For example, when it received data changes from websocket, it would call this.setState on the appropriate state item, triggering UI changes (for example a new TODO being added to the list of TODOs) to its child components. I found redux to be a good replacement for this.

However, when it came to maintaining a different kind of state - say the current state that the user is on - I found it quite difficult to use redux because I had to essentially maintain my own history of screens independently from the Navigator. It also becomes difficult when there are nested navigators and it becomes unclear to which state "back" should take the user.

I'm wondering what are some good rules of thumb, or situations, where it would be appropriate to use this.state vs redux vs not manually keeping the state at all (like using Navigator).

like image 429
fanghai44 Avatar asked Dec 25 '22 11:12

fanghai44


1 Answers

Generally, Redux sits above your "smart components" feeding them only the bits of global application state they are meant to handle. I would say that generally one would always store state in their Redux store unless the state being used is literally internal the component's function and would never be of use elsewhere.

An example of this might be storing the value of a textInput field where the value isn't itself the part that interests other components, perhaps it's compiled together with other values or you only want to make it available to other components once it meets some length requirements or something. In such a case I'd store it in my component's state prior to ultimately stashing it in the redux store.

State storage "Rules" that I personally follow:

  1. As soon as a value is of any interest to any other part of the app, may be of value later, or will be passed to other components (smart or dumb), it MUST go into Redux
  2. If a value is literally nonsense to the rest of your application, it MAY be managed internally to the component via that component's state until such time as it is subject to the above.

Regarding your specific issue of navigator not knowing what "back" is, why not instead implement your route state as an array instead? You can further write your component-that-wraps navigator's mapStateToProps function to only look at the last item in the routes.

mapStateToProp(state) {
    return { currentRoute: state.route && state.route[state.route.length-1] }
}
like image 112
Adam Terlson Avatar answered Dec 27 '22 01:12

Adam Terlson