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

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.

Related

Shall we globalize all the states of a react application?

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 -

State Variables vs Redux in React

Which one of the two scenarios is preferred?
Use state variables to store the value from the backend/server and use it directly in all the components(Eg: DataTable) present on the Page.
While calling the APIs, that data will load in Redux store. So instead use the data from the redux store directly in all the components.
Case 1 : When to use Local React State
React state is stored locally within a component. When it needs to be shared with other components, it is passed down through props. In practice, this means that the top-most component in your app needing access to a mutable value will hold that value in its state. If it can be mutated by subcomponents, you must pass a callback to handle the change into subcomponents.
Case 2 : When to use Redux state management
When using Redux, state is stored globally in the Redux store. Any component that needs access to a value may subscribe to the store and gain access to that value. Typically, this is done using container components. This centralizes all data but makes it very easy for a component to get the state it needs, without surrounding components knowing of its needs.
Case 2 should be preferred.
When the data is used in multiple components and is coming from the backend, you should store it in a redux state.
Keep any state that can be called "Application State" in the redux. If that object somehow is defining some part of your application and not just a state of a component(e.g. showSpinner, isEditMode, etc) then it's your applications state and should be kept in the redux store. That's kind of my definition of difference. Also, note that you should always keep only JSON serializable object in your redux store. Also, I mostly consider data from backend to be a part of "Application State".
So I think that your data should be stored in redux. Technically you have on advantage when using redux store in your case as redux triggers component updates only when the data is changed. So using it here might give you some performance benefits as well.

Should I use Redux when component state is local

I have a component which has some local state (form validation error messages). This component does not get its state from a parent, nor does it passes these values to any of its children.
My application uses Redux for global state management. Should I push this state to be managed via Redux, or keep using local state for this particular component.
The simple answer is NO. -Simply because you already have all the necessary data in the only relevant component where you're actually using it.
Redux (react-redux) is used for app level state management.
So, here comes the longer answer -If you at some point decide that you need the data in various components and also that they need/ should be accessible at any point, Redux is definitely a great option.
It all really depends on the amount of data and the need for effectively passing the data throughout the entire app.
On the other hand, if you only have to pass data between Parent - Children components, Redux could be an overkill, because you can still achieve it using just React by passing (exchange) values between various components via props.
So, if you only need that data inside only that component (Component level state), Redux it's a no-go because it's pretty large and it wouldn't be of any use for your case.
Sounds like the data is only needed for this component, so you don't need to push it to the Redux state.
Yes, if you take the way of an immutable state and connected components and you would avoid unecessary re-render.
In this case, you can connect your field to it's state, and rerender the error message only when an error occur.
I would not save this to Redux state.
Unless you require this data elsewhere.

Where should I store the local state of a Redux middleware?

Iā€™m using Redux to manage the logic of a music player. When itā€™s playing something and suddenly fails, I want to be able to intercept that action and make the player start again, but only n times, as I don't want to keep automatically retrying forever if the problem isn't recoverable.
I think a middleware is a good option to implement this, but Iā€™m wondering if I should store the number of retries already done for a certain item either in the global state, or locally in the middleware.
A more general question would be if a Redux middleware should contain any local state at all, I mean, state that only it cares about.
In my opinion (and based on limited information about your specific project):
you should configure the n value via the middleware constructor, and
you should store both n and totalRetries in private variables of the middleware.
Why?
Choosing where to store your middleware state shares similarities with deciding between component state and redux state. You can use the same questions as a guide:
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)?
As Dan Abramov said:
The way I classify it is when ever state needs to be shared by multiple components or multiple pages and we need to persist some data over route changes, all that data should go inside the redux store.
You can map this idea from components to middleware by rephrasing "ā€¦persist some data over route changesā€¦" to "ā€¦persist some data over [insert relevant boundary here]ā€¦", for example closing and relaunching the app.
The totalRetries doesn't seem to represent a meaningful state of the application. It has to do with some "behind-the-scenes" I/O operation that wont persist across closing the app or sharing app state with a debugger. One might even argue that you should not expose it to other components via redux state, lest they rely on (potentially shifting) internal workings of your middleware.
redux-saga, etc allow us to write this type of functionality in a very neat and testable way without having "exposed wires" in the application state or module namespace. You could use a saga to encapsulate your entire "play audio" behavior.
Exporting a reducer and then accessing its compartmentalized "public" state from your middleware introduces quite a bit of unnecessary complication.
If you want to expose totalRetries and n to other components, you may do so via an action, such as PLAY_AUDIO_RETRY with the action containing both variables in its payload.

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.

Resources