Reputation: 1395
My question is, should I still be using stateful React components or should I move that state into the Redux store?
Upvotes: 1
Views: 1114
Reputation: 14419
I recommend reading this Medium post: Presentational and Container Components. It outlines the ideas of using component state for UI state but non-UI state is global (redux). It also suggest a pattern of how to approach that by having container components responsible for managing access to the global state and simple view components that the container passes state to as a prop.
So the answer is a little more complicated in my opinion because there are different types of state.
I highly recommend this free video series that goes into Redux in depth and provides a lot of explanation to build your knowledge up quickly: Getting Started with Redux.
After digging into Redux more and using it on a project to learn, I found myself making use of it to store UI state. The particular use case was a long scrolling div
. I wanted the scroll position of the div
to be the same when the back button was used. It was super easy to hook the click up to a dispatch to update the state for the current div.scrollTop
and then on componentMount
(back button pressed, component remounts) simply set the div.scrollTop
to the position from state.
So I think it can be very useful to have UI state in Redux too. It is easier to reason about and simple to do. I can see building very powerful UIs this way that do not exhibit the typical UI issues seen with single page applications.
Upvotes: 2
Reputation: 1696
There is no single true answer for you question.
You have different types of states. You have a state of your models (in terms of MVC) and UI (View) state. In classical MVC your models should not depend on UI. So, here we have a question: is it ok to save UI state (inputs, checkboxes state) in global redux store.
The most general rule, in this case, is to use common sense :). You can choose any of the approaches depending on your needs and it will be ok if it suits better for your situation.
But, let's look at several examples.
I know apps, that save whole UI state in global redux store. I mean that every keystroke in any field will fire event and will update the global store.
Pros:
Cons:
For example, you have a form. And your form manages the state on your inputs by its own. So you just render it as <Form onSubmit={ (fields) => saveFields(fields) }>
Pros:
Cons:
Some general ideas that can be useful:
Upvotes: 5