DEV Community

Cover image for Props vs. State
Hadil Hijazi
Hadil Hijazi

Posted on • Edited on

Props vs. State

What is React.js?

React can manage your data and properly render your application when your data changes. Below I will it explain it in the most simplest way possible.

There are two main ways with React.

Props and State

Props

Props are arguments to a function.

When a component is created inside a react and you want to render it, you will pass the props that you want to give it.

For example: A counter application

What you want to pass, is the initial count. Essentially what your count should start at. So you're going to pass your counter components' initial count inside the props.

In the counter app, the initial count should be 0. So, we need to pass that through in the props.

Image description

Props is used for things you pass to functions. They are what you want to initialize your component to or what you want your component to render like.

Another time Props can be used is for if you want to display something to the user that has a title and a subtitle.

It also needs to be stored in the Props because what you want your component or function to take is going to be the Props.

In our case, the component is stored in the title and the subtitle. So we’re passing them through the Props.

Then, the app knows if those Props change at some point. If something else in the application changes those Props it will rerender that component for us. Because our Props are now different.

Props if useful for displaying information inside a component without hard coding it. Essentially, it’s available to a function.

State

State is something inside a component.

Props is something you pass into a component.

State is handled inside that component and you can update it inside the component.

Props are handled outside the component and must be updated outside the component.

In the counter app, the current up to date count is handled inside the state.

So, while we pass the initial count in the props, we’re setting the state to the initial count and inside of our component that is handled in our counter. We managed to update our counter to increase it or to decrease it depending on what the user does. And we’re using state for that.

State is used when you make changes inside the application it will rerender that section of the app.

State is helpful for when you want to update or rerender your app based on something the user has done.

If you want to change something in the app, you need to store it in state so it properly rerenders when it changes.

State is also good for inside a form on an application.

If there is an input element, checkbox/select box, that needs to be updated by the user state will be used to store what they are updating the value to.

Image description

Top comments (0)