States and Props in React: What are they and how to use them?
Hey everyone! In my previous blog, we got familiar with JSX and in this article, I will try to explain States and Props in React. As we all know One of the core concepts of React is the use of components, which are reusable pieces of UI that can have their own logic and data. However, how do we manage the data inside and between the components? This is where states and props come into the picture. So let's understand them.
What are states?
Basically, a state is like a variable that exists inside a component, that cannot be accessed and modified outside the component, and can only be used inside the component. It 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.
A state can be used to store any kind of data that is relevant to the component, such as user input, form values, UI state, etc. A state can be modified using this.setState
, which is a method provided by React to update the state object and re-render the component. The state can be asynchronous, meaning that it may not update immediately after calling this.setState
. A state is also known as the local state or the internal state of the component. It is owned by the component itself and can only be changed by the component itself.
What are props?
Props or “Properties” are read-only components, that give a way to pass data from one component to other components. It stores the value of attributes of a tag and works similarly to the HTML attributes. For example, if we have a component called Greeting
that displays a message with a name, we can pass the name as a prop to the component like this:
<Greeting name="Shivam" />
Then, inside the Greeting
component, we can access the prop using this.props.name
and display it like this:
class Greeting extends React.Component {
render() {
return <div>Hello, {this.props.name}!</div>;
}
}
Props are immutable, which means that they cannot be changed once assigned. They are also read-only, meaning that they cannot be modified by the child component that receives them. Props are used to communicate between components and pass data from parent to child components.
Difference between states and props.
States and props are both used to store data related to a component, but they have some key differences:
States are mutable and can be changed by the component itself, while props are immutable and can only be changed by the parent component that passes them.
States are used to manage data inside a component and control its behavior, while props are used to pass data from one component to another and customize its appearance.
States are owned by the component itself and cannot be accessed by child components, while props are owned by the parent component and can be accessed by child components.
States can only be used with class components (before React 16.8), while props can be used with both class and functional components.
States make components dynamic and interactive, while props make components reusable and configurable.
Examples of using states and props.
States~
Suppose you want to create a counter component that allows the user to increment a number displayed on the screen. Here's how you can do it:
import React, { useState } from 'react';
function Counter() {
// Define a state variable called "count" and a function to update it called "setCount".
const [count, setCount] = useState(0);
// Define a function to handle the increment button click.
const increment = () => {
// It will update the "count" state by increasing it by 1.
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
Now, let's break down how this code works:
We import the
useState
hook from React. TheuseState
hook is used to define and manage state within functional components.Inside the
Counter
functional component, we use theuseState
hook to create a state variable calledcount
and a function to update it calledsetCount
. The initial value ofcount
is set to 0.We define a
increment
function that will be called when the "Increment" button is clicked. Inside this function, we callsetCount(count + 1)
. This is where the magic happens: whensetCount
is called with a new value, React re-renders the component and updates the value ofcount
to the new value (in this case,count + 1
).In the JSX portion of the component, we display the current value of
count
using{count}
within a<p>
element. We also have a button with anonClick
event handler that calls theincrement
function when clicked.
Props ~
Now let's take an example to understand props. Suppose you want to create a 'User' component that displays the name and age of a user. You want to pass the user's information as props to this component. Here's how you can do it:
import React from 'react';
function User(props) {
return (
<div>
<h1>Name: {props.name}</h1>
<p>Age: {props.age}</p>
</div>
);
}
export default User;
Now, let's break down how this code works:
We create a functional component called "User."
Inside the "User" component, we expect to receive data through props. In this case, we expect two props:
name
andage
.Within the JSX portion of the component, we use
{
props.name
}
and{props.age}
to access and display the values of thename
andage
props, respectively.To use the "User" component in another part of your application, you would import it and pass the necessary props:
import React from 'react';
import User from './User'; // Assuming User.js is in the same directory.
function App() {
return (
<div>
<h1>User Information</h1>
<User name="John Doe" age={30} />
<User name="Jane Smith" age={25} />
</div>
);
}
export default App;
In this example:
We imported the "User" component into an "App" component.
Within the "App" component's JSX, we use the "User" component twice, passing different values for the
name
andage
props. For example,<User name="John Doe" age={30} />
and<User name="Jane Smith" age={25} />
.These props are then received and used by the "User" component to display the name and age of each user.
In summary, props in React allow you to pass data from a parent component to a child component. They enable you to make your components dynamic and reusable by customizing their behavior and content based on the data you pass in as props.
Conclusion:~
States and props are two of the most important concepts in React that allow us to manage data inside and between components. States are variables that exist inside a component and can be changed by the component itself. Props are attributes that are passed from one component to another and cannot be changed by the child component. States are used to make components dynamic and interactive, while props are used to make components reusable and configurable. By understanding how states and props work, we can create better and more efficient user interfaces with React.
I hope now you are pretty much familiar with props and states in React. Now go and practice on your own and practice by taking another example. Then only you will be able to understand this.
In my next blog, I will explain "conditional rendering" and "composition".
Thanks for reading 😊.
Subscribe to my newsletter
Read articles from Shivam Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shivam Jha
Shivam Jha
LFX'24 @Kyverno | Web Dev | DevOps | OpenSource | Exploring Cloud Native Technologies.