Understanding state and props in React
If you’re a beginner in react development, you’re probably wondering or haven’t grasped what state and props really are . Not to worry , we are going to treat them in this tutorial.
There’s is no other better way to understand this than to build an app that utilizes them both. So In this article , we are going to build a simple app and feed it with fake data.
Before we start building the app , let me give a brief explanation of what state and props are.
A state is used to hold and access data in a component. A state is only accessible to the component in which it was created. It cannot be accessed by an external component. This is where props comes in. Props are used to access the state in another components. I think thats the easiest definition to it. Think of a restaurant or fast food eatery without a drive through or an online food ordering system. You have to actually go into that fast food restaurant to get food. The state in this illustration is the food being sold in the restaurant, only accessible to people within the restaurant. So, think of props as the online ordering system or the drive-through, this allows you to get food without actually being inside the restaurant building. I hope that simplifies it.
Now let’s start with the app. I use create react app. So here we go;
Now that we have our app running ; let’s create a component ViewFakeData and a set of fake data.
Now we have two components app and ViewFakeData and our fake data
Now, in our parent component, App, we’ll add a constructor and a lifecycle method componentDidMount, initialize our state to be empty in the constructor, then set the state to the fake data we created.
Next thing is to map our state to the ViewFakeData component tag in our parent component.
Now, that how state is initialized and used. If we were to render the data in our state right within the component app in which it was declared, we would just map our state directly to a set of HTML tags and it will render right in that component. But for this tutorial, we won’t be stopping at just the state. Now that we have mapped the state to the component tag ViewFakeData, we go to the ViewFakeData component and use the props as shown below;
If you run the app, you should see something like this;
So, that’s one way to use state and props in react. If you enjoyed this tutorial, kindly follow my medium page here and on twitter @toyesebalogun.