React — Props and State Explained

Mariola P
3 min readOct 11, 2020

--

What are Props?

Props, short for properties, are arguments passed into React components via HTML attributes.

You can think of props as a way of passing data from component to component. Props can be any value including: strings, objects, arrays, functions, etc. They enable us to make our components more dynamic, and more reusable.

For example, let’s say we have a <BlogCard /> component which has a title, an image and content as attributes or properties. If we hardcoded our <BlogCard /> component it will look like the below:

But if we wanted to display a blog card for another blog we would have to write another component, which would be silly. Instead, we can use props in our component:

Now, with props our code does not only look a lot cleaner but it is much more reusable compared to the previous example.

Props are passed from their parent to child components. To pass props to a component, you add them as attributes through JSX curly braces. Props are ‘immutable’ and should not be modified or changed inside the component.

What is State?

In React, a state is data that is mutated or changed in your component. Unlike props, a component’s state can change during the component’s life.

If we wanted a component’s props to change, we will need to send new props from its parent component. With state we can maintain and update data within a component without requiring its parent to send updated information.

To illustrate how the state works, let’s say we have a simple component which displays a counter, when a user click it should increment the counter by 1.

The state is initialised in the constructor:

Updating a component’s state

State should not be modified directly, to update it we use a built-in method called setState(). So, to alter the state our increment method we make the use of ‘setState’:

Initial State vs ‘setState()’

We set the initial state in the constructor method because the constructor runs first when a component is made. After we have given a component with its initial state we can then update with the setState() method. It is important to note that setState() is asynchronous.

Summary:

  • Props are immutable
  • Props are passed from parent to child
  • State is for values that change
  • We set initial state in the constructor and update state with setState()

Resources:

--

--

No responses yet