Shall we globalize all the states of a react application? - reactjs

I have a question regarding the state management when using redux. the main aim of Redux is to globalize the state of the components so every component in the App can read and update that state.
My question is: When we write React/Redux applications, which design pattern we should use? to define every state in the Redux store? or to only define the states that require to be read by other components in the Redux store, and the rest will be encapsulated inside their relative components?
I think you got my question right? :D
Now, how about components' reusability? doesn't redux make it impossible for the components to be reusable?
& Thank yous 😘

There is no “right” answer for this. There are some Recommendations though -
Some common rules of thumb for determining what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point - in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already - there instead of re-requesting it)?
Do you want to keep this data consistent while hot-reloading UI components (which may lose their internal state when swapped)?
From Redux Github -
Question: How to choose between Redux's store and React's state? #1287
dan_abramov - Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft.
Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local).
The rule of thumb is: do whatever is less awkward.
Cheatsheet -

Related

Is it a bad practice to use stateful components bypassing redux?

Say, I don't want to keep my checkboxes state in global redux store. Cause I don't want to deal with actions and reducers for this small local state. So I want to explicitly use setState() inside my component.
Is it a bad practice (for instance, in testing aspect)?
Per the Redux FAQ entry on component state vs Redux state:
Using local component state is fine. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.
Some common rules of thumb for determing what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
It's absolutely fine to keep the checkbox state in you local state as long as it doesn't depend on the data.
A good practise is to keep all you data in your redux store and the ui-related state in you local store.

Should you store Application state in local state or Redux Store

I have been working with Redux for almost a month now. My question is this that I am putting all my app data in the redux store, but should I also put the toggle states that helps me change my UI in redux state or should I simply manage that locally in each page by just doing
this.setState({ showActiveForm : false })
There is no right or wrong answer for this. To help you decide, here are some common rules of thumb taken directly from the redux documentation:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given
point in time (ie, time travel debugging)?
Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?
Another advantage to keeping the majority of your UI state in redux is that you can write more stateless functional components and make use of the performance optimisations they will bring in future versions of React:
This pattern is designed to encourage the creation of these simple components that should comprise large portions of your apps. In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.
The current best practice is to use local state to handle the state of your user interface (UI) state rather than data.
Your case is the perfect example of the above. So the state to manage hiding and showing of a component must be within the local state itself and not redux store
Another example of UI data that you could store in local state would be the currently selected tab from a list of options.
A good way to think about when to use local state is to consider whether the value you’re storing will be used by another component. If a value is specific to only a single component, then it’s safe to keep that value in local state.
To elaborate further
Redux is also useful for triggering events for which you need access on multiple components or across multiple routes. An example of this would be a login modal, which can be triggered by a multitude of buttons all across your app. Rather than conditionally rendering a modal in a dozen places, you can conditionally render it at the top-level of your app and use a Redux action to trigger it by changing a value in the store.
Usually, the rule of thumb is that you use a redux store to manage data in your application aka storing items fetched from the server and local react state for ui behaviors, like toggles in your case. But it's not a strict rule, for instance, if you need to toggle something from multiple places it's easier to use redux for that
That depends on how your components are organized. If the state of toggle is used across multiple components then I prefer to manage the state via redux store.
If the the status is local to that component and if it is not used in anywhere else best thing to do would be managing the state within the component. Therefore the component will be self contained.
3 points that i consider when working with react redux
1.keep UI state and transitory data (such as form inputs) in local state.
2.keep data that you intend to share across components in Redux store.
3.Data that you fetch from Server should go to redux store.

What to store in redux state?

I'm building a medium-sized React/Redux app, and I've become very comfortable with React - however, Redux is still a little hard to wrap my head around.
I understand that I can use connect() from Redux to connect any Component or Container to Redux state. However, I'm unclear on when to do this - is it based on complexity? How many props would need to be passed down to child components?
What are the factors I can use to determine when to use connect()?
Edit to provide an example: -----
For example, I'd like to include a messages area for users inside my app, particularly a badge showing number of unread messages. Would I simply connect() any component where I'd like to display the badge?
I DON'T agree about storing all component state in the store. I prefer having in the redux store only data that matters to application as a whole and thus other components may benefit from this global accessible shared data.
Having component specific state in the store, that only matters to this component, is a overkill and useless IMO.
You store the state of your app in redux. How you structure your state tree is up to you. You can think of the state tree as one giant javascript object. With redux, you would ideally store as little component state in your react components themselves and instead move that to the redux state tree.
For example, if you fetched some user data, you could store that in the redux state such that your connected components have access to that data now. You can also get more granular and store states that describe certain UI components. A part of your state that describes a dropdown could look like this
{
myDropdown: {
isOpen: false,
options: [
'apple',
'orange'
]
}
}
I believe a good point to start incorporating redux is when your app gets to a certain point where your components are no longer just "dumb" components that display data.
Edit:
To try and answer the question "when should I connect my components?". I struggled with this myself but don't have a great answer yet. Right now I typically connect a component if I am passing down props through many ancestor components just for that component specifically. So connecting would avoid that boilerplate code altogether.
Official REDUX page:
https://redux.js.org/faq/organizing-state#do-i-have-to-put-all-my-state-into-redux-should-i-ever-use-reacts-setstate
Some common rules of thumb for determining what kind of data should be put into Redux:
Do other parts of the application care about this data?
Do you need to be able to create further derived data based on this original data?
Is the same data being used to drive multiple components?
Is there value to you in being able to restore this state to a given point in time
Do you want to cache the data
List item
But...that means in most of off applications the only data what I should store in Redux store is the logged in user data. That is the only entity which attributes influences all the screens (role, login name, user settings).
Usual applications do not need to remember entered data between screens, cache, history....
Very confusing, so I am not really sure any more what to put in Redux store...

React components with shared state that are far away

I am new to React so please excuse me if this is a noob question but I really could not find the answer in the DOCs or elsewhere.
Let's say I have two buttons with a counter that share the state but are far away from each other in terms of the placement in the UI.
The documentation says the common owner component for both buttons should own the state. It makes sense if the components are next to each other like in the example but what if my buttons are each part of a different UI group and are far away in terms of nesting? My state holder would be the root of the document and I would have to pass a handler function down through many layers. And what if I need to add new component somewhere else that also needs to know the state? Would I have to modify all the parent components in the way to pass the state down? That is tremendously impractical.
Without React I would have some global Subscribe/Publish pattern like jQuery Observer and all UI elements could subscribe/publish to it regardless of their nesting position.
How does React solve this?
Related question: If I need to load/save the state to DB, how do I pass a reference of the controller (or Whatever) to each React component that stores the state?
1 for global state you may use REDUX
Redux is a predictable state container for JavaScript apps
for connect/subscribe component with that state ,you should use react-redux
If components are far away in terms of nesting, you may connect/subscribe them to redux store, and take only neccessary part of state. They will update if only neccessary part is changed.
article that explains how you can do your case
to learn how to use redux you can watch this videos from creator of redux (Dan Abramov)
1.getting-started-with-redux
2.building-react-applications-with-idiomatic-redux
3.I definitely recommend to you discordapp rectiflux channel. because you allways can ask any question online.(there you can find contributors of that tools)
2 alternative way that less verbose then redux is MobX
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). The philosophy behind MobX is very simple:
Anything that can be derived from the application state, should be derived. Automatically.
I suggest to look at the Flux stores. In short, stores are like model in your application. You can listen to change (subscribe) and also modify their properties (publish). You can see how it was done in example app.
A better option is to go with Redux.
Redux is enabling use cases like yours in a way simpler fashion :)
It will help you with all the state and make your life much easier.
Some good resources for learning:
The Redux Website
Video courses from Dan Abramov, the creator [Free]
Awesome course on Udemy [Not free]
Building Applications with React and Redux in ES6
And finally take a look at this youtube series [Free]
Managing state in the middle layers of your app should be avoided where possible. This data belongs in a store, which holds the global state of the app. Then each component accesses the state via its props.
The naĂŻve approach to get the data down to the component is to pass the store through all the layers of your app "manually", i.e. through props.
Smarter alternatives exist, which use connected components, that access the global state through the context (as opposed to the props). Typically, the presentational component (your button component) is wrapped in a container component that handles this connection to the store, then passes the data in via props.
There are numerous frameworks that facilitate this process, links to which are already provided in the other answers.
If you are trying to share simple states, try this ( I am the author): react-provide-state
Otherwise I will recommend Redux. It has become the most popular tool for managing application states.
In the applications being working on, we use Redux to manage the main application states and almost all other states. But we use 'react-provide-state' for simple, UI only states like Modal, Checkbox states.

In Redux, should global state replace component state?

My question is, should I still be using stateful React components or should I move that state into the Redux store?
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.
global redux store for everything
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:
It is easy to track state changes when the whole state is in one place.
You can serialize the whole state for debugging purposes. It can be automatic state saving on errors. Or QA engineer can dump UI state with a special keyboard shortcut and send to developers. Developers can take this serialized state and restore whole UI as it was on QA's machine.
Cons:
Rerender the whole app on every keystroke.
A lot of intermediary state (in global store) that is needed only while user entering some data.
Passing state down to your components. You will use "Container" components for this but the question is should your "Container" components be only top-level components or you should wrap leaf dump components in containers. Both variants are acceptable but in most cases it is better to move state higher (while it makes sense). Read about "Smart vs Dumb" components or "Containers vs Presentational components"
You should manage different types of state (from different sources) in one global store.
UI state in your components.
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:
Intermidate form state is private to form. You can think that this state does not exist at all, it does not matter for you.
The shape of private state is much easier to change.
Components are more coherent. They are more independent, like simple mini applications inside your larger application.
Cons:
Other components cannot access this state.
There is no single place of storing state.
Different appoaches to state management.
Increases possibilty of situations when there will be more than one source of thruth.
Additional resources:
Presentation from ReactConf 2016 about possible options for managing state in ReactJS apps
Dan Abramov's great post about "Container" and "Presentational" components
Great video tutorial from Dan Abramov "Getting started with redux". It shows how to use presentational components and how to manage app state.
Some general ideas that can be useful:
Handle as less state as possible in your components but not less than required. Stateless components are easier to work with. But remeber that the state will be moved somewhere, so you will need to handle it in any case (it can be store, or presentational wrapper component etc).
Make your components as much independent as possible. You can make good independent components with private state or make them stateless.
Split components into presentational components (context independent) and container components (context dependent).
Move state as high as possible. Prefer saving state in upper level components. It can be not only container components. You can create presentational components that wraps you stateless components just to manage state (they will have no connection to redux)
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.

Resources