State Vs Prop / Arrow Functions React

Posted by amandarebecca89 on February 5, 2019

I was asked by my instructor to answer two questions more in depth, so I hope that if you are struggling with these two concepts that this will help you.

Question 1: “Why use state vs. props?”

Let’s define state and props: State is data that can change during a components life. Props(property) does not change the data and lets us pass values into the components. Props also help make components dynamic but they have limitations where State does not. For props to change it will need a parent component to send it to a new prop and remake itself. With State you don’t have to worry about that! It changes without requiring a parent to send information. Props contains information that should not be changed,and State contains information that can be changed like the method setState. This method updates the state object and then re-renders the component.

In conclusion, we want to use State for “mutable data” aka data that will change and we use Props when we want to pass data from parent to child.

Question 2: “Why do you use arrow functions in React?”

An arrow function looks like this: handleOnClick = (event) => { event.preventDefault(); this.setState({stars: this.set.stars +1}) }``

An arrow function is from ES6 Syntax and should be used anytime that “this”’ is required to be bound to context(this) and not the function itself. Moreover, we don’t redefine the value of “this” within the function body. By doing this, it makes it easier to predict behavior when passed as a callback, like handleOnClick in the above snippet - so we know that when you click the button the number of starred item will increase by one each time. It is important to note that you can’t use arrow functions for object methods and that they are anonymous meaning that they are not named.