React: Props & State Explained

Yoel Yukalo
2 min readFeb 9, 2021

--

Props, short for “properties”, is used for passing data from one component to another. However, the data being passed is uni-directional, meaning it can only be passed from the parent to the child.

The state of a component is an object that holds information that may change over the lifetime of that component.

Using Props

Ex. A parent component is including a child component while including a prop by calling:

<ExampleChildComponent color=blue/>

U can access the props passed by the parent, inside the child component that we named “ExampleChildComponent”:

class ExampleChildComponent extends React.Component {
constructor(props) {
super(props)
console.log(props.color)
}
}

Using States

Unlike Props, States are stated inside of the constructor within the component:

constructor(){
super();
this.state={
count: 0,
};
}

The example above demonstrates data that is hardcoded, however, the data states have can actually be props. This is helpful because props cannot be changed but the components state can.

Note: React cannot change elements, because it needs to be rerendered every single time you want to update it. There is a solution to this: introduction ‘setState’.

setState

The state can be updated in response to event handlers, server responses, or prop changes. setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.

Let's use setState() to update the number of followers a user has:

updateFollowers() {
this.setState((prevState) => {
return { count: prevState.count +1}
});
}

setState is capable of running asynchronously, so instead of updating the state directly, it needs to take a callback function. The state object will be updated & re-render the component asynchronously.

--

--