Why use props in react if you could always use state data? - javascript

I understand that there's two ways to pass components data: props and state. But why would one need a prop over a state? It seems like the state object could just be used inside the component, so why pass the prop parameters in markup?

Props are set externally by a parent component. E.g.;
render() {
return <ChildComponent someProp={someValue}/>;
}
State is set internally, and often triggered by an user event within a child. E.g.;
handleUserClickedButton: () {
this.setState({
buttonClicked: true
});
},
render() {
return <button onClick={this.handleUserClickedButton}/>;
}
So, props are a way for data to go from parent to child. State is a way for data to be managed within a singular component, and possibly have changes to that data triggered by children. In effect, they represent data traveling in 2 opposite directions, and the way in which they are passed is entirely unique.

There are two ways to "pass" or access data from outside your component but state is not one of them.
The two ways are:
Props - which a parent component pass down to the child component.
Context - which you can "skip" the direct parent in the tree.
The state is an internal object which no other component has access to it unless you pass it explicitly (via the two ways mentioned above).
So basically your question is not accurate as you can't really compare the two.
I think what you are really asking is why using a state-less instead of a state-full component.
Which you can find an answer here in Stack-overflow or in other websites.
Edit
A followup to some of your comments.
why does the child not just have a shared state? for example, each
component (or sub-component) could just do a "this.state" to get the
current state of the program
The same way you can't share or access private objects in other
functions.
This is by design, you share things explicitly and you will pass
only what the component needs. For example, look it this page of
stack-overflow, lets say the voting buttons are components, why
would i pass them the whole state if it only needs the vote count
and 2 onClick event listeners? Should i pass the current logged in
user or maybe the entire answers rendered in this page?
so you can't pass state between a parent to child? for example, can't
the parent change the state and then the child gets the new state
This is exactly what the props or context should do, provide an API for sharing data between parents and children though we keep it in a one way data flow, from parents to children, you can't pass props upwards. but you invoke handlers passed down to your child components and pass data through that handler.

Related

Is it good practice to pass component instance as props to another component in VueJs?

Assume that we are going to make a text edior.
When typing, Component C(Text input section) needs the state of Component B(Font stlye picker) to determine what style to use.
We can share that state by Vuex, but in OOP, related logic or variables are better to be put in same class, and when other components need the state of that object, just to refer it directly.
If I want to refer components directly, one way is to save some components when they are mounted, and pass them as props to other components as the following.
// in <template>
<FontStylePickerVue ref="stylePicker" />
<TextInputSectionVue
ref="textInputSection"
v-bind="{
tylePickerComp: stylePickerComp
}" />
//in Main Component <script>
mounted(){
this.tylePickerComp = this.$refs.stylePicker;
}
data(){
return { tylePickerComp : null }
}
In Vue, although there are many ways to communicate between components, I never seen any of them passes component instance as props directly like this.
(it works, and very convinient though.)
I know doing like this, in a way, it make system more complicated because components refer each others in a complex relation, but I'm just wondering if there is any design pattern like this in Vue, or doing like this has some cons like low perfermance ,etc.
In the end, in order to clarify the idea, I want to compare what if I pass component as props directly or use common methods in this example:
Pass component as props directly:
Need to save component reference on mounted, but type declartion is once and for all(ex. use InstanceType). Need to deal with null(it's null before mounted).
Event bus:
Emit an event with a promise resolve function as callback to make other components to resovle with their state. This is good because it will keep data or logic in the same class(compare to use Vuex), but you need to write your method in a promise style in order to read resolved result.
Vuex:
Split some variables into global scope, and this is not so compatible for cases which are better to gather logic and data at same place.
Just want to get some idea for this topic, sorry for long article.

React classes in main component constructor

Let's say I have a lot of app state to manage in my React application.
Therefore, I would like to split the state into smaller, manageable chunks.
For example I have the following main component with state and methods that alter this state.
class App extends Component {
constructor(props) {
super(props);
this.state = {
foo: ['some', 'items'],
bar: [{ arr: 'of objects'}]
}
}
changeFoo() {some code in here...}
changeBar() {some code in here...}
}
The state and methods written in the App component are getting out of hand. Yet it must be written in the App component since the state is passed to other components as props.
How would you usually manage this?
When you see that the state of your React application is getting out of hand, it's usually time to bring in a state management library like Redux (there're a few and Redux is the most popular one).
It'll help you have a global state that is managed in a reasonable way.
When we see how React works. It is based on one-directional data flow.
So, usually the Application state is kept at the top most Component (Say, App Component) in your case. So that data/state can be passed down as props to the component that needs it.
There, however may be the cases where children components of the parent, needs to work with the same data(Say in case of an event - a button click that happens in the child component.) In that case we write a function in the parent component and pass the function as props to the children, so that the state gets updated in the parent itself and any child gets updated data.
In pure React (without using any state management library), we have to pass the state as props to work with our app. But in case you choose to use a state management library such as Redux, then the components (known as Containers) can directly communicate with the Application State.
And If your application state contains objects within objects(like you have shown) or Array of Objects containing more Objects, then you cannot use setState() to update the state directly. In most of the cases, you take copy of the state and then use JSON.parse(JSON.stringify(state)) to do deep cloning and work with the state in a best possible manner.
There are other things in the example, the functions that you have used within the class , you need to bind the scope of this variable to point to the current class. This we do inside the constructor method, or simple make use of arrow function in order to avoid errors.
If you need more explanation, I will share with you :)
One solution is to make a generic change() function with a parameter for the key that should be changed:
change(key, value) {
setState({key: value, ...this.state});
}
Now when you want to add a listener to a child component:
<Foo onChange={ value => change('foo', value) }/>
<Bar onChange={ value => change('bar', value) }/>

How to transfer states among components?

I'm new to React JS, I want to create a ToDo list app. I have App.js which is the main page and so I have created MainBlock component for App.js page which holds left and right side of my layout and in right side property it loads Form component which has input and button and saves input values to an array in state and in left side it loads List component which has a property named allTasks which prints all tasks.
My problem is how can I transfer allTasks state from Form Component to App.js to pass it to List component property?
In App.js :
<MainBlock
left={
<List allTasks={['خرید از فروشگاه', 'تعویض دستگیره درب منزل']} />}
right={
<Form />
} />
You can accomplish this by storing the tasks as state in the App component, and have Form pass up the state through a callback prop. This concept is called "lifting state up". Here's a guide about it: https://reactjs.org/docs/lifting-state-up.html
<MainBlock
left={
<List allTasks={this.state.allTasks} />
}
right={
<Form onSubmit={allTasks => this.setState({ allTasks })} />
}
/>
Let tasks be a state of the MainBlock component. Pass this state down to the List component.
Let the Form component expose a callback property (maybe onTaskCreated) which is invoked when user complete creating a new task.
Let MainBlock intercept onTaskCreated callbacks and update it's internal state with the new task, which causes it to re-render and thus passing down the new task list to the List component.
You are trying to achieve two way binding here. Unfortunately, React is a library that doesn't support two way binding by default.
You can only pass in the values from Parent to Child to Sub-Child. However, the reverse is not true.
In this case, you are trying to load props from Form to App that is from Child to Parent which is not possible.
You should make use of state containers such as Redux that overcomes this limitation by making the state of one component available to the other component.
You can store all your tasks in the state of the MainBlock component and pass functions to update the state by your form. Also, pass the state (tasks) of MainBlock to your List component. Updating your tasks to MainBlock will automatically pass the tasks to List. Later you could use a state management library like MobX and Redux.
It can be confusing passing data between components. Libraries like redux were created to make this "easier", but it can be done with simple React. To pass state information to children, you pass it into their props. To send data the other direction, you pass (from parent to child) a handler function that is called from the child and can affect the state of the parent (or be passed to it's parent) as needed.
I wrote a sample pen to help people wrap their heads around this. Hopefully it helps.
Something like:
<Child1 handleAdd={this.handleAdd.bind(this)}
handleSubtract={this.handleSubtract.bind(this)}
/>
calls in the parent and and is accessed in the child as:
<Button onClick={this.onAdd.bind(this)}>
add
</Button>
<Button onClick={this.props.handleSubtract.bind(this)}>
subtract
</Button>
Then there is a function in the parent called handleAdd that can affect the parent state.

react.js does not update DOM after having changed state array

I am trying to implement a game in react where I have the board as an two dimensional array in the initial state of the parent class. Tiles are rendered by iterating through that array. I pass those children a function as a prop so that they can change that state array.
Now, when I use that function to change the array, the HTML does not update. The array gets updated when I call setState but it never rerenders. I tried this.forceUpdate() but still no luck. What I then did was to pass a function from that child to the parent through the function to update that child's state and this works, but I need the function from the parent to call itself recursively to update the board. I feel like I might have hit an anti-pattern. How could I change my code in order for the DOM to update, please?
There is parts missing but those are all the components involved. statusBoard is the internal version of the board featuring the solution. I hope this is clear.
Whenever you are linking props and state together you have to create a componentWillReceiveProps function like so:
componentWillReceiveProps: function(nextProps) {
this.setState({
positionX: nextProps.columnPosition,
positionY: nextProps.rowPosition
});
}
When games state changes and passes it down as props to Field, fields own internal state doesn't get updated at that point because it is relying on its own state. this is an anti pattern and you should avoid Field having to have any state and just rely on its props it gets passed and have a parent component that is handling the state of everything.
https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

How to perform child component validation without infinite loop in react.js

I have really simple example in react. Parent component pass data to the child component throug props. Inside child component i can change this data, also new data can be passed to the child component from the parent at any time. Also on the parent i have save button. After pressing it i should show validation message if some validations did not pass.
I have implemented it in such a way. From parent i pass callback to notify parent that validity of the data has changed. Inside child i perform validation in three places:
componentDidMount - to validate initial data
componentWillReceiveProps - to validate data that can be passed from the parent
onChange to validate entered data
Any time child perform validation of data i call callback to inform parent about validity. The problem is in componentWillReceiveProps. With setState in parent this part causes infinite loop - see picture below.
Please check jsfiddle Here in console you can see that i restricted infinite loop to 10 iterations to prevent you browser from crash.
As you can see there is infinite loop - because React call componentWillReceiveProps in not too smart way - every render cycle instead of callind it only when props actually changed.
I am really would like to know what is the react way to solve this issue. Should i store child state only in child ? I also tried to store child validity in parent out of state - but my coworkers said that this is not react way - why ?
Here's how I see your challenge:
you want to have your validation method in your child component, because it is specific to this type of child (e.g. a password input field). - but in react, no outside component (except grandchildren) are allowed to directly call this method.
you want your parent to know about the validaty of each of the children components (e.g. to determine of all the fields validate and a form submit is allowed) - so you need the result of the validation method in the parent component, and this must be state
Your co-workers are correct: react does not like you storing component-wide variables outside of state. Because such variables are completely independent from react lifecycle methods etc. and would get you in debugging hell quickly.
I would advise you to make following changes to prevent the endless loop:
do NOT store the validity of the child in the child state. Save the result + any message in the parent, and pass it as a props to the child. Child only renders the props.
implement shouldComponentUpdate(), which checks if any of the props or state variables have changed. If not return false, otherwise, return true.
move your call to validate() from componentWillReceiveProps to componentWillUpdate(). This ìs called after shouldComponentUpdate(). So only if props or child state have changed, will validation (and re-render) take place.

Categories

Resources