State and Props in React

State and Props in React

In React props are a way to pass the data or properties from parent component to child components while the state is the real-time data available to use within that only component.

States and props are two of the most important concepts of React and everything in React is based upon them.


State in React:

A state is a variable that exists inside a component, that cannot be accessed and modified outside the component, and can only be used inside the component. Works very similarly to a variable that is declared inside a function that cannot be accessed outside the scope of the function in normal javascript. State Can be modified using this.setState. The state can be asynchronous. Whenever this.setState is used to change the state class is rerender itself.

Props in React:

React allows us to pass information to a Component using something called props (which stands for properties). Props are objects that can be used inside a component. Sometimes we need to change the content inside an element. Props come to play in these cases, as they are passed into the component and the user..


Difference between props and state:

PROPS

  1. The Data is passed from one component to another.
  2. It is Immutable (cannot be modified).
  3. Props can be used with state and functional components.
  4. Props are read-only.


STATE

  1. The Data is passed within the component only.
  2. It is Mutable ( can be modified).
  3. The state can be used only with the state components/class component (Before 16.0).
  4. The state is both read and write.


Importance of using hooks in Functional Components

Functional components are initially stateless but we use hooks to manage state in functional components. For functional components, we use useState hook.


  • useState hook:


Before using useState hook, we need to import useState hook from react inside our component.

import { useState } from "react";        

While declaring, useState accepts an initial state and returns two values:


  • The current state.
  • A function that updates the state.


In the above image, count is the current state and setCount is the function that updates the state and the initial state is 0.

After this, I created an addition and subtraction button where the state of the count changes on the click of those two buttons:

Thank You So Much Bikash Karki Sir


#LearningReact #MERN #NMC #Day6

要查看或添加评论,请登录

Yujan Ranjitkar的更多文章

社区洞察

其他会员也浏览了