Tobenna
Posted on April 3, 2023
In React apps, the two most used concepts are props
and state.
props
allows developers to pass data from one component to the next, and state
enable the component to manage data internally.
Understanding these two concepts will make you a better ReactJS developer.
The props
and state
are like the elevator and electricity in a 10 storey building, you can manage without them but be prepared to work like an ant.
This article will highlight the differences and how props
and state
can be combined to solve problems.
Before we dive in, let's look at the content.
Introduction
- Explanation of React's props and state concepts
- Why understanding props and state is important for building React applications
Props
- Definition and explanation of props
- How to pass props from parent to child components
- How to access and use props in child components
- Best practices for working with props
State
- Definition and explanation of the state
- How to set and update the state in a component
- How to use the state to trigger re-renders
- Best practices for working with state
Differences between props and state
- When to use props vs. state
- How to decide which to use in a given situation
Working with props and state in practice
- Examples of using props and state in real-world React applications
Conclusion
Introduction
Passing data from one component to another makes your React application functional. If you want to manipulate and manage data; build complex and dynamic user interfaces, you will need props
and state.
Why understanding props and state is essential for building React applications?
Props help pass data from one component to the next; this is important because it allows the reusability of components. Props also assist you in creating a clear separation of issues between components, making it simpler to control the complexity of massive packages.
We use the state
method to manage data and manipulate the conduct of a single component. The state is mutable, which means that you could update it with the aid of the component itself, any adjustment to the state cause a re-render of the component.
The state
method lets you create dynamic and interactive interfaces that reply to user input and other events.
By understanding props
and state,
you could create nicely-organized, reusable, and maintainable code in React.
You can also create extra complicated and interactive user interfaces that offer a better user experience. In addition, expertise in props
and state
is vital for debugging and troubleshooting problems in React packages, as many mistakes in React are related to props
and state
management.
Definition of props
In React, props
, short for property, is a way to transfer data from a parent component to a child component. A prop can be numbers, strings, arrays, or objects.
Props are defined as key-value pairs in the parent component before a child component collects them as an argument. There can be more than one child component using the same parent data.
How to pass props from parent to child components
Simple steps are needed to pass a props
from a parent to a child component.
In the parent component,
- You declare a component like so
<ChildComponent/>.
- You define the props in pairs,
name of props = value of props
inside the declared component. It should look like this
<ChildComponent
name= "Alice"/>
We put everything together
function ParentComponent() {
return (
<ChildComponent
name= "Alice"
age={30}
hobbies={['reading', 'swimming', 'cooking']}
/>
);
}
How to access and use props in child components
You can create as many child components as you want. And they can all access the same parent data.
You can access the props
by calling the props
object passed as a parameter to the component.
The props
are accessed via the key names defined in the parent component.
First, we pass props to our child component as an argument
function ChildComponent(props){}
We can now access each data by its key name as an object of props.
->
props.keyName
.
Putting everything together, we have this
function ChildComponent(props) {
return (
<div>
<h1>Name: {props.name}</h1>
<p>Age: {props.age}</p>
<p>Hobbies: {props.hobbies.join(', ')}</p>
</div>
);
}
Best practices for working with props
Here are some best practices for working with props in React:
-
Use descriptive prop names: Use descriptive and meaningful names for your
props
to make your code easier to understand and maintain. Avoid using abbreviations or single-letter names. -
Define default props: Define default
props
for your components to ensure that they work properly even ifprops
are not passed from the parent component; doing this can prevent unexpected errors and improve the robustness of your code.
MyComponent.defaultProps = {
prop1: defaultValue1,
prop2: defaultValue2
}
-
Validate props: Use
prop types
to validate the types and shapes ofprops
passed to your component. Validated props can help catch errors early and provide helpful error messages.
import PropTypes from 'prop-types';
MyComponent.propTypes = {
prop1: PropTypes.string.isRequired,
prop2: PropTypes.number,
prop3: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number
})
};
- Avoid modifying resources: Resources should be considered read-only, and you should avoid modifying them in the child component. If you need to change data passed from the parent component, copy the data to the child component level or use callback functions to update the parent component.
- Keep code simple: Keep your code simple and easy to understand. Avoid passing large or complex data structures as parameters, as this can make your code difficult to manage and debug.
By following these best practices, you can write secure, error-proof, and efficient code when working with resources in React.
Definition and explanation of the state
In React, state
is used to represent the current state of a component. It is a way for the component to re-render itself and manage its data based on the state change of that data.
It is a commonly used concept in react applications. For instance, when you click on the menu icon, you are changing the state of a mobile menu from open
to close
.
The state is also useful for user interaction and is local to its component, meaning it can't be accessed or modified from another component.
How to set and update the state in a component
In React, we can have a class or function component (not part of this article).
And in a class component, we can set and update the state using the setState().
In the component's constructor, we will define the state of the component:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
We created a count state in the constructor and set it to zero.
If you are using a function component, then this is what you will have
import React, { useState } from 'react';
function MyComponent(props) {
const [count, setCount] = useState(0);
}
Here, we used const
to declare an array and initialize it to a state hook.
Any method works fine.
How to use the state to trigger a re-renders
In React, a state change will trigger a re-render, which will usually cause the user interface to update or change a value. It happens so fast that you wouldn't notice the "refresh" it does.
To trigger a re-render in a class component, we can call setState()
with an argument as the updated state value.
handleClick(){
this.setState({ count: this.state.count + 1});
}
The method handleClick()
will increment the count by one and update the user interface immediately.
If you are working on a functional component, then you will have to create a function and then pass it to a button, like so
function handleClick() {
setCount(count + 1);
}
---------------------------------
-------------------------------------------
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
Here, we used the useState()
hook instead of setState()
to define the initial state of MyComponent
and a function to update it.
The useState
hook allowed us to create count
, the state value, and setCount
that triggers the state.
Differences between props and state
The props
and state
in React are handy, but they have differences. Their purpose, flow, scope, and accessibility are not the same.
I created a table to make it simple.
When to use props vs. state
Props and state are two concepts used in React to manage and pass data within components.
Props are helpful when passing data from a parent component to the children components. They are unchangeable and allow you to configure and customize any child component based on the parent's needs.
A child component can only read Props and push through the component's tree. If the parent's props change, React updates the child components.
Props are useful for/when:
- You want to transfer data from the parent to child components.
- The transmitted data is immutable (unchangeable).
- You may want to configure or modify the child section based on the parent's needs.
- You want to provide a way for parent components to communicate with child components.
The state is useful for managing component-specific data that are bound to change. The state is mutable and controlled by its components.
The component can define and update its state using the setState
or useState
method in React. Unlike props, it doesn't wait for the parent component before it changes its state.
We use state
method for/when:
- You must manage and update component-specific data that can change over time.
- The data is internal to the component and not required by other components.
- You want to re-render the component when the state changes.
- You want to implement interactive behavior within a component.
How to decide which to use in a given situation
A few factors to consider before deciding which concept to use in a given situation. They include
Relationship among components: The components' relationship can tell which concept to use. If the data needs to move from the parent component to its child component, then
props
is best used here. But if the data need to be managed internally within a single component, the state might be more suitable.Data Immutability: Does the data change over time? If it doesn't, then
props
are preferred. Else, if you expect them to change better to usestate.
Component reusability: Storing props at the parent component is for reusability. If you want to use the same data across different components, then
props
is suitable. Butstate
is not suited for reusability.Component responsibility: What is the purpose of the component? If the component needs to respond to the user's interaction and manage its data, then
state
is suitable. While we can useprops
if the component's purpose is to render and present data passed from its parent.Performance and efficiency: The component's performance is also a factor to consider. A frequently updated component will work well if you use
state.
If the data is not frequently updated, thenprops
will get the deal done.
Please don't treat this as a rule; they are considerations that guide you when trying to pick which to use. And with time, it becomes an unconscious decision for you.
Working with props and state in practice
Let's look at simple examples of state and props
Examples of using props and state in real-world React applications
- ** Props example**:
Let's work on a simple ToDo List component; its job is to receive an array of to-do items as
props
from its parent. The Todolist component would go through each item in the array and render them accordingly. The parent component contains the unchangeable to-do list items and passes them down to the child component before it is rendered on the user interface
export function App() {
const todos = [
{ id: 1, task: 'Finish project', dueDate: '2023-05-31', completed: false },
{ id: 2, task: 'Prepare presentation,' dueDate: '2023-06-05', completed: false },
// more to-do items...
];
return <TodoList todos={todos} />;
}
// Child Component
function TodoList({ todos }) {
return (
<div>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</div>
);
}
function TodoItem({ todo }) {
return (
<div>
<span >This task: {todo.task}</span>
<span> is due by {todo.dueDate}</span>
{/* ... */}
</div>
);
}
And you see this on your screen.
- State example: Let's use a counter-component for this one. This counter will keep track of a value and allow users to increase or decrease it. The value stored in the component's state and changes due to user interactions:
import React, { useState } from 'react';
export function App() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(prevCount => prevCount + 1);
};
const decrement = () => {
setCount(prevCount => prevCount - 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
You can click the increment or decrement button, and the count value changes immediately.
The count is at -2 because I clicked on decrement twice
Conclusion
When you create an application in React, understanding how and when to use state
or props
makes development more straightforward.
A props
is used if we want something to remain the same; for example, your tweet doesn't change no matter how many times it's quoted. But the likes, quotes, retweets, and bookmark count increase and decrease frequently and state
will be suitable here.
This concept can be confusing for beginners but if they understand their differences and how they work together. It will become simple.
Posted on April 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.