Why is redux state not mapped to react state? - reactjs

I am very very new to React-Redux and encountered a method called mapstatetoprops.
However why is redux state not mapped to react state ? Why is it mapped to props instead ?

In React, state belongs to the component while props are passed to the component from it's parent. mapStateToProps() is a function that is used inside connect() to pass data from the Redux store to a component.
The difference between state and props: https://codeburst.io/react-state-vs-props-explained-51beebd73b21
If you want to use data from the Redux store in a component's state, the component would first need to receive it as a prop. You would then be able to map it to the component's state in getDerivedStateFromProps. https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
When you derive state from props this way, updating the component's state does not change the Redux state.

The primary reason (as I see it):
"Dumb" components deal only with properties, not state.
One motivation for "dumb" components is that they're trivial to test: all you need to do is pass in props. This means that regardless of where the props come from the only thing you're testing is that they do the Right Thing with whatever props they're given.
Mapping the redux store to properties reinforces this notion. Once you introduce component state you then have to play more (some easy) games to test the component, but it's not as straight-forward as a pure component.

Cause this is the Redux workflow.
When without redux you use local state (component state) and passes data through parent to children, this makes data sharing very difficult when you have more components.
ComponentOne have data to be passed to component 4:
ComponentOne -> ComponentTwo -> ComponentThree -> ComponentFour
With Redux, you have a store, but can't use is as a object (getters and setters), you map it's contents to the components that needs each property.
Redux scenario:
store {userName: "user", otherData...}
Dashboard
function mapStateToProps(state) {
return {
userName : state.userName
}
This way the component will listen to userName changes, but only can change data in the store through the mapDispatchToProps. This way, the Single Source of Truth React principle is assured.

Related

Get Current component state and store it in redux

How to get latest updated react component state (after all the state changes are done) and put the same object in Redux.
Get the latest state and dispatch an action (with a copy of current state) only once instead of dispatching the same action from different methods where state is getting altered ?
Is there any efficient way to achieve this ?
First If your state doesn't need multiple pages then no need to store the state in the redux, use local state.
But if you want to use redux and want latest state, then if you want this state in the stateless component(functional) then you can use useSelector redux hook for the latest data, and if you want the state in the stateful component then use mapStateToProps.
useful links:
for hooks: https://react-redux.js.org/api/hooks#useselector
for mapStateToProps: https://react-redux.js.org/using-react-redux/connect-mapstate#defining-mapstatetoprops

How its better to work with Redux useSelector in React Hooks

I'm new in React Hooks and I'm wonder how its better to do some things. Example the state how its better to keep the state in parent and to pass to the child or to put the state in every component where I need the state? Witch is the good option?
Generally, if you use some state values in only one component, you can make it the state of that specific component, making it self-contained.
If a state is used in a component and some of its child components, it's a good idea to store it as a state in the component and pass it as props to child components.
If a state is used in multiple (relatively unrelated) components in an app, you can store it as a global state (through redux or context API) and use it in those components.

Does React Redux recreate the entire Virtual DOM each time an action is dispatched from the Store?

Isn't that a very expensive affair?
For example, if I clicked a button that toggles something... Does React need to recreate the entire Virtual DOM just for that one action and diff it as well?
When you call React Redux's connect on components, you're wrapping them in a component called Connect. The component reads the store from the <Provider>'s context. When you dispatch an action, the Redux store gets updated, which causes all connect-ed components to get new props (those defined in mapStateToProps during a store update.
If a connected component subscribes to a store field but the action doesn't change that field's value, it wouldn't re-render.
The rest follows regular React rendering rules. If a connected component's HOC wrapper subscribes to a store field that has changed, it will update and cause the connected component to re-render as well. You could implement shouldComponentUpdate in the connected component if you don't want it to re-render.
References:
https://github.com/reduxjs/react-redux/blob/master/src/components/Provider.js
https://github.com/reduxjs/react-redux/blob/master/src/components/connectAdvanced.js

Putting props to state in react

I'm working with react-redux in a current project and on my search for react wisdom I came across a 'convention' I don't understand.
Other programmers tend to put a prop to state right in the constructor. Why is that?
I've never seen it in the official documentation and from there I learned that these two are two different things to hold and share data.
Is there any use in it or mybe just a personal preference?
Thanks.
It sounds like a pattern for when you need some initial value from outside the component, but then want to either ignore, or not immediately affect, the outside (by for example dispatching Redux actions on each value change).
For example, maybe you have a form that should be prefilled with some values that the component gets from the outside (Redux state) through mapStateToProps or similar. You could let every form fields onChange dispatch an action that changes the Redux state, causes the incoming props to change, and then re-render the form with the new value. Or maybe you find that to be overkill. Maybe you're satisfied with keeping the changing form data in the component internal state until the user actually submits the form, and only then dispatch an action that will post the form data, change the Redux state and pass new props (like success status) down to the form component.
Yes, it is possible, especially when you want to keep things simple by not using container components or flux / redux store to manage application's state.
A component can manage its own state, and the initialState will be assigned as the props passed from its parent component.
Consider the following example:
class TodoList extends React.Component {
constructor(props) {
// Assign todos property to state so that the TodoList component
// can self-manage this value without interacting with outside components.
this.setState({ todos: props.todos });
}
...
addTodo(todoDescription) {
this.setState({ todos: this.state.todos.concat[todoDescription] });
}
}
However, I still do recommend to separate the view components and data manipulating components when your applications is complex.

React props states and Redux

What is the different between states and props?
How can you pass a value of let's say CompomentA to ComponentB if we have have for example ComponentA which takes an input then ComponentB is suppose to output(to print it on the screen) that same value if we have a third component called CompomentContainer which is a container of both A and B?
What is Redux? the definition of redux on the main website does not make sense to me. How does it work exactly? How is it useful to react?
Please bear with me, I hope my questions make sense. Thank you.
Those are very valid questions. I've been there and I know how frustrating it is to read about redux and not understanding anything. For some reason people like to use fancy words, which sounds complicated but in reality things are very simple and easy.
What is Redux?
Redux is a Flux architecture. In simple words it will help you to manage the global state of your app.
How does it work exactly?
Redux will create a single "store", this store will have all the data that you need to render in your components, you can update the data using "actions", you will call the actions from your components, these actions will transfer the new data to the "reducers", inside of a reducer you will basically copy the data from the components to the global state (reducers should be pure functions).
How is it useful to react?
It's very useful! Mainly because you will be able to share data across components. Also by having a global state you could save it to the local storage (or a database) to add offline support.
What is the different between states and props?
You can define props to describe the properties that the component will receive when creating instances, you can think of props like parameters, for example:
<MyComponent name="Crysfel" lastname="Villa" />
The previous component is receiving two props, name and lastname. Props will allow you to send data from ComponentA to ComponentB, assuming ComponentB is a child of ComponentA. Props will also help you to receive data from redux. As a rule of thumb, you should never modify the value of the props, these values are just to receive data.
State on the other hand is an object that might contain configurations for your component, the idea is to handle the state of the component, for example a collapsible container, you could have a toggle property in the component's state and toggle the value when user clicks a button. However when using redux you will rarely use the component's state, because Redux is managing the state of your app.
For your second question about sending data between component, you would use redux for that, ComponentA should call an action and send the new data to the global state, then redux will update your component with the new data and then you can render the new data into ComponentB (using props).
What is the different between states and props?
State is data that is tied directly to the React component in which it is set. Props is data that is passed into a child component from the parent component. Unlike state, props are immutable and never "set" directly.
How can you pass a value of let's say CompomentA to ComponentB if we have have for example ComponentA which takes an input then ComponentB is suppose to output(to print it on the screen) that same value if we have a third component called CompomentContainer which is a container of both A and B?
To pass value from Component A to ComponentB you would provide the value as props, passed in via the ComponentA render function. Something like this:
class ComponentA extends React.component {
render() {
return <ComponentB myvalue={value} />
}
}
In ComponentB the value can be accessed: this.props.myvalue
What is Redux? the definition of redux on the main website does not make sense to me. How does it work exactly? How is it useful to react?
Redux is an implementation of the ideas of Flux with a few architectural differences. You can think of it as a library that helps you create a central data store that passes data one-way into React components. It allows you to maintain global state outside of the components themselves.
A top-level container component typically listens to the store and re-renders whenever the store data changes (see the connect function). The data is then passed from the container component into the children components that need that data so they can render properly.

Resources