Programming

What is the difference between props and states in React?

In this article, I will try to explain the difference between props and state where we should use props and where we should use state. To understand props and state we first need to know about React. What is react and why is it used?

React js

React is an open-source font end library used to make web pages and it’s maintained by Meta (normally Facebook), React can be used to develop single-page applications now at this time it has become a very famous UI library. React allows us to customize as much as we want, so we can create multiple components.

That’s why Props are used to pass data from one component to another component or state is the real-time data available to use within that only component.

So first we’ll create a react application.

npm create vite@latest

Example code

After creating the React application Here is necessary to npm install and then start the React Application > npm run dev

Folder structure

Fig: Project structure

Props

Props is a well-known property that can be used to pass data from one component to another component in React. Props are immutable means they cannot be modified props.

Send Props example code

This is an app component here is an object this object’s name is the user this user object sends ReceivePropsComponent.

Receive Props example code

user object Receive here and show the user interface, This props value is immutable just read-only. Here is just an example of props drilling with the object but you can pass any type of value string, number, boolean, array, or object.

Output

Start the React app

npm run dev

State

Inside the react state represents parts of an Application that can change. The state is mutable means the state can be changed or modified.

Example code

The app component declares the count state using the useState hook in React. when clicking the Click button then execute the HandleClick function and change the state count value. Count state initial value is 0 when clicking the click button then change state and change count value.

Output

 

Difference between props and state

Props State
Data sends one component to another component. The Data is passed within the component only.
Props are Read-only and can’t be changed or modified props. The state can modify and change the value
Props are immutable. State is mutable
Props can be used with state and functional components. Inside the react state represents parts of an Application that can change.
Props can access child component The state can’t access from child component

 

What is your reaction?

0
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly

Leave a reply

Your email address will not be published. Required fields are marked *