State vs Props in React

State vs Props in React

A thorough understanding of state and props

ยท

3 min read

When you think about DATA in React, There are two main ways to manipulate DATA in React.

Props and states.

Understanding the difference between states and props requires an understanding of what a STATE and PROPS are.

Props:-

  • In React, props are what allow components to communicate with one another; for instance, the Parent component can pass data to the Child component as props.

  • Props are like arguments to a function. In React Props are arguments passed into React Components.

  • You can pass props to any component as we declare attributes for any HTML tags.

  • Props are used when you want to display some information inside of a component without hard-coding it.

Example:-

The Parent component wants to display Name, but in order to ensure reusability, the Parent component does not want to hard-code a value of name, so the Child component provides Name as a PROP to the Parent component.

Multiple props in a single component:-

So, Props are how you initialize the component or how you would like to render a component.

State:-

  • The state is a built-in React object that is used to contain DYNAMIC DATA about the component. The state is handled inside the component.

  • The useState hook declares a state variable that holds the state and a function also known as setState that can update the state. Moreover, the state variable can be initialized by passing a value as initialState to the useState hook.

  • The state change can happen as a response to user action or system-generated events and these changes determine the behavior of the component and how it will render.

  • Whenever the state changes, the component re-renders.

  • The State of a component may change over the component's lifetime.

Example:-

Think of the application that helps deposit and withdraw money from the bank. In this application, the value of the account balance needs to be re-rendered every time a user performs an action. This is where the state comes in,

  • In the above code, the count is declared using the useState hook with 10000 as its initial value.

  • The component renders two buttons, first incrementing the value of count by 1000 and the other decrementing the value of count by 1000.

  • To update the value of the state variable, we have to pass the new value to the function declared using the useState hook.

In short, PROPS can be used when you want to display static values without hard-coding them or when you want to pass values to a parent component from a child component or vice versa. On the other hand, State can be used to display dynamic data or to change the value of a variable as a response to user action or system-generated events.

Find me :)

Did you find this article valuable?

Support Divy Parekh by becoming a sponsor. Any amount is appreciated!

ย