ReactJS: Understanding Props and State
Let's start with a short and smart introduction to React.
React is an open source javascript library for building user interfaces, which is created and maintained by Facebook. It is declarative, efficient and flexible and we can create interactive UIs with ease. It's a component-based front-end library and is only responsible for building rich user interfaces.
Out of all the concepts that React has, let's focus on React Props & React State in this blog. They are the two important concepts essential to react development and are fundamentally different.
We are going to cover in detail about Props and State separately and then wrap up with their fundamental differences. Let's start the learning with the help of an example project in ReactJS.
I. Project Installation
To understand better, let us create sample projects in ReactJS using Npm and Yarn.
I.a Steps to Create React Project by Npm
Step 1:- Create a React application using the following command
Step 2:- Once the project folder is created i.e. folder name, move to it using the following command
I.b Steps to Create React Project by Yarn
Step 1:- Create a React application using the following command:
Step 2: Once project folder is created i.e. folder name, move to it using the following command
I.c Run the project
Using npm,
Using yarn,
I.d Project Structure
Refer the image to understand how the folder structure looks once the project is created.
I.e Package.json
Refer the image to understand the package.json once the project is created
II. Props
II.a What is Props?
Props are the short form of properties. It is an argument or optional input that is passed to the react component. It is a method to pass the data from one component to another component. It cannot be modified, is read-only and is immutable.
Props are just an object that contains attributes and their value passed from the parent component.
Props Structure:
Example: Modify the App.js & App.css file with the below code.
App.js
App.css
Create a sample component <<Hero.js>> for receiving the props
Run the application with yarn command from the root directory of the project
II.b How do Props work with different data types?
Send props to a component by passing the props data type - object
The image shows App.js that includes the Hero component. First, we need to add a "person" attribute as a prop to the Hero Element and pass the superHero object as a value to that person attribute.
The component received the arguments as a props object and the props value can be read with [props.attributename]
OUTPUT:
Let us check console.log(props). As mentioned earlier, props are just an object that contains attributes and their value passed from the parent component.
console.log out
Props cannot be modified. It will crash the application and show the error. It cannot be assigned to read only property 'name' of object '#<Object>' because it is read only.
Example:
Send props to a component by passing the props data type - variable
The image shows App.js that includes the Hero component. First, we need to add a "person" attribute as a prop to the Hero Element and pass the superHeroName variable as a value to that person attribute.
The component received the arguments as a props object and the props value can be read with [props.attributename]
OUTPUT:
Send props to a component by passing the props data type - string
The image shows App.js that includes the Hero component. First, we need to add a "person" attribute as a prop to the Hero Element and assign the string value to that person attribute.
The component received the arguments as a props object and props value can be read with [props.attributename]
OUTPUT:
Send props to a component by passing the props data type - array of object
The image shows App.js that includes the Hero component. First, we need to add a "persons" attribute as a prop to the Hero Element and pass the superHeroList array of object as a value to that persons attribute.
The component received the arguments as a props object and the props value can be read with [props.attributename]
OUTPUT:
II.c Can we do de-structuring props?
Yes! we can do de-structuring props with the ES6 Features.
How to do de-structuring props?
method: 1--> () => level and method: 2 --> {} = props
method: 1 --> () => level
method: 2 --> {} = props
II.d How to send props to in class component?
The image shows App.js that includes the Hero component. First, we need to add a "person" attribute as a prop to the Hero Element and assign the string value to that person attribute.
The component received the arguments as a props object and the props value can be read with [this.props.attributename].
In addition, refer to the image to see how to do props de-structuring in class?
OUTPUT:
II.e how to use props for the children component?
The image shows App.js that includes the Hero component. First, we need to pass the children inside the Hero open and close tab.
<Hero> // children goes here...</Hero>
Example: Here the children's component is passed as a p tag with a text inside the Hero open and close tag.
The component received the arguments as a props object and props value can be read with [props.attributename]
OUTPUT:
Note: We can also send the data from children component to parent component by using function calling.
III. State
Next, let's understand State.
State is a built-in React object that contains data or information about the component. A component's state can change over time, whenever it changes,
the component re-renders. It is mutable and is local to the component alone. It can be accessed or modified only on the inside or directly by component.
Diagram representation for state
Example: App.js
this.state is an object and the state object has a property called name initialized to the string value. Now bind state value with curly braces within the render method - this.state.name
OUTPUT:
III.a Changing State
State is totally different from props. we can use this.setState() method and pass a new state object as an argument.
The only place where this.state can be assigned is in the constructor. Any time to change the state, this.setState() method has to be used.
Example: App.js
OUTPUT:
III.b How to update State?
- Do not update the state directly. The reason behind this is when the state is modified directly, react will not re-render the component.
- Update state like this,
- Alternatively, Update state by using the Callback function method
- Write Better React JS
OUTPUT:
If increment is clicked, the expected value should show the incremented number. But in the console, only the previous value is shown. So the console value is 1 less than the rendered value. This is because calls to setState is not synchronized.
Here, console.log() is being called before the state is actually set. So, we need to execute the code only after the state is updated. To handle such situations, call back function can be passed in as a second argument.
setState() method has two parameters, the first parameter is the state object and the second parameter is a callback function.
To avoid this kind of console.log(), try below
OUTPUT:
III.c Can we do de-structuring in state?
Yes! we can do de structuring state with the ES6 Features.
How to do de-structuring in state? method: 1 --> {} = props
Example:
const { message } = this.state
IV. Stateful component and State less component in React
React has two kinds of component - Stateful & Stateless
Stateful components hold some state whereas stateless are components with no state. Both these components can use Props.
Prior to React v16.8, the functional component is stateless but post React v16.8, the React team has introduced hooks in react. With the help of that, specifically with useState hook, functional component has been changed as a stateful component.
Example:-
const [value, setValue] = React.useState(1)
When to use stateful components?
-
when the data is dependent on state for rendering and
-
when interactive elements need to be built
When to use state less components?
-
when reusable code is needed
-
when there is no requirement of state
V. Props Vs State
VI. Wrapping up
React Props and State are two important concepts that play a crucial role in creating dynamic and interactive user interfaces and these are explained in detail with sample projects and programs with essential differences are also highlighted. This guide can be used to know how to use react component efficiently.
If you're looking for experienced ReactJS developers to bring your projects to life, look no further.
Our team of experts has a deep understanding of React Props and State, & other concepts, and they're ready to bring their expertise to your projects.
Contact us today to learn more about how we can help you with your ReactJS needs.
Recommended Articles:
Gowtham
I am a Web Developer with Front end and React native app development experience, specializing in JS,ReactJS, TypeScript,Next js.