React state management with redux vs lifting state up - reactjs

After reading reacts lifting state up, it made sense how shared state was held by the parent and it would then pass it as props and re-render as needed. However with redux we can have state in the store. Then is it okay to violate the top down data flow and have sibling components interact via redux? Or they should still update the parent state and have the parent re-render them?

Reading the question and answer as of when I post my answer here, I'd like to further add to Bryan's statement using the official Redux style guide:
Prefer having more UI components subscribed to the Redux store and reading data at a more granular level. This typically leads to better UI performance, as fewer components will need to render when a given piece of state changes.
For example, rather than just connecting a <UserList> component and reading the entire array of users, have <UserList> retrieve a list of all user IDs, render list items as <UserListItem userId={userId}>, and have <UserListItem> be connected and extract its own user entry from the store.
This applies for both the React-Redux connect() API and the useSelector() hook.

If siblings are interacting via Redux, the communication is still top down (because they aren't communicating with each other โ€” they're communicating with Redux).
Sibling A dispatches a redux action
Some reducer updates the state
Sibling B updates based on the new state
Using connect from react-redux eliminates the need to manually pass props down through an entire chain of components.
Ultimately, where and how you manage state in an app depends on a lot of different factors. There's no right answer here. I've seen both strategies used within the same app.

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 -

Can I use state in components while using Redux or Redux store?

**Is it OK to Using a component state for just to handling form data, while the main data and other stuff of the application will be stored in the Redux store?
I don't want to use redux-form instead manually dispatch it to the reducers**
Redux comes into the picture when we want to manage the state across different component. It provides a centralize store where state of all the components are managed.
When talking about forms, in most cases form data is only limited to the component is which is being used. So, in that type of scenario there is no need to link them to centralized store using redux. A simple way is to store them in the component state and get it processed. Afterwards, you can store the output of that in redux store according to your needs.
It is okay to do that. You can keep a local state in the component. state = {} in class components, const [localState, setLocalState] = useState() for functional components.
Or you can use custom hooks for handling your local state needs. Check out useInput or useForm custom hooks that are developed by the community.
Yes of course. Some things go best in component state, some go best in a parent component, some go in Context, and some go in Redux. There is little use in putting everything in Redux, it just causes a lot of boilerplate and every component tries to update when the store changes.
You put things in Redux when different components that are at different places in the HTML tree use the same data, and it changes during the app's lifetime (things like the user's language don't change often and go in Context). You use it when you want to store your app's state to restore it later (which exact menus are currently open or closed is usually not that important) and when you want to keep track of state changing using the Redux dev tools.

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.

When do I choose React state Vs Redux Store

I've been learning Redux and a part I'm unclear of is, how do I make a determination between using react state vs redux store and then dispatching actions. from my reading so far it looks like I could use React state in place of Redux store and still get things done. I understand the separation of concerns with using Redux store and just having 1 container component and the rest of it as stateless component but how do I make the determination of when to use React state Vs redux store is not very clear to me. Can someone please help?
Thanks!
If the state doesn't need to be shared with other components, or the state doesn't need to be keep when the component is unmounted, then you can just put it in the component's state.
You can think that the Redux store is the database of front-end, if you have something like product data fetched from an API, then the Redux store is the right place; if you have a dropdown component, which takes a isOpen prop, then the parent of that dropdown can just keep dropdownIsOpen as a component state.
For more information, here is the answer from Dan: https://github.com/reactjs/redux/issues/1287
Also you said
only 1 container component and the rest of it as stateless component
This is incorrect. You can have several container components. A container component can also contain another container component.
From book:
First of all, we should always keep in mind that only the minimal
amount of data needed should be put into the state. For example, if we
have to change a label when a button is clicked we should not store
the text of the label, but we should only save a Boolean flag that
tells us if the button has been clicked or not. Secondly, we should
add to the state only the values that we want to update when an event
happens, and for which we want to make the component re-render.
Another way to figure out whether the state is the right place to
store information is to check if the data we are persisting is needed
outside the component itself or by its children. If multiple
components need to keep track of the same information, we should
consider using a state manager like Redux at the application level.
There are a few things that need to be grasp
State of component: If you want to keep state-specific to your HOC then use state. Now in the function component, we use useState.
State of redux: If you want to share data throughout the application use redux state.
Store of redux: It's nothing but a database for the redux library. In the case of redux, we can have only one store. To use multiple stores we can use Flux but it will make things more complicated.
You're absolutely right. Redux (and flux architecture in general) are only formalism tools to help for building large apps. They're not necessary at all.
There's actually an interesting post called You might not need redux by Dan Abramov, the creator of redux that might give you a better answer than I do: https://medium.com/#dan_abramov/you-might-not-need-redux-be46360cf367#.7093fm1z8
If state is needed only for that particular component then prefer to use react state.
For example using state for UI actions
If any state you want to use across the component/project then go with redux state.
For example API response data etc
For detail understanding refer this link
https://spin.atomicobject.com/2017/06/07/react-state-vs-redux-state/

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...

Resources