In React, understanding the distinction between state and props is mandatory for managing data within components effectively. It's also crucial for building React applications efficiently. Hence, this topic will help you learn about their differences.
A quick recap of state and props
In React, state serves as an internal data storage within a component that can change over time. A component itself owns and manages state. To commence a state in function components, the useState hook is used.
Here's an example:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};In this example, the count state variable starts with a value of 0. The "Increment" button triggers the increment function, which updates the state using the setCount function. As a result, the component will re-render, showing the updated count in the UI.
On the other hand, props, short for properties, are read-only data that can be passed from a parent component to its child component. Props allow data to flow from the parent to its child components. Here's an illustration:
import React from 'react';
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
const App = () => {
return <Greeting name="John" />;
};In this example, the name prop is passed from the parent component (App) to the child component (Greeting). The child component receives this prop and can use it within its function. The Greeting component will render a personalized greeting based on the name prop.
Comparing state and props
Now that you have a common understanding of state and props, let's highlight their differences.
Imagine a UserProfile component that showcases user information as props:
function UserProfile(props) {
return (
<div>
<h1>{props.name}</h1>
<p>{props.email}</p>
</div>
);
}
// Usage
function ParentComponent() {
return <UserProfile name="John Doe" email="[email protected]" />;
}In terms of state, let's examine a ToggleSwitch component that adjusts its appearance based on its current status:
import React, { useState } from 'react';
const ToggleSwitch = () => {
const [isToggled, setToggle] = useState(false);
const handleToggle = () => {
setToggle(!isToggled);
}
return (
<div>
<button onClick={handleToggle}>
{isToggled ? 'ON' : 'OFF'}
</button>
</div>
);
}
export default ToggleSwitch;Ownership and Control:
A component owns and manages state. It carries and updates its internal data. For instance, in the examples above, the
ToggleSwitchcomponent holds its own state,isToggled.Props are designed by the parent component and received by the child component. The child component, however, is not allowed to modify its props. In the example, the
UserProfilecomponent receivesnameandemailas props from the parent component.
Mutability:
State stands for mutable data which can change over time. You can update it using relevant state update functions. In the case of
ToggleSwitch, when you click the button, it triggers thehandleTogglemethod, leading to a change inisToggled's value.Props are read-only and cannot be modified by the child component. They are used to display data or pass behaviour from parent components. The
UserProfilecomponent uses its props to display user details but cannot transform the values ofnameandemail.
Re-rendering:
Changes in states trigger the re-rendering of the component. This allows the UI to update as per new state values. In the
ToggleSwitchexample, every state change causes a re-rendering of the component. Therefore, the button text updates whenever it is clicked.Same way, changes in props also lead to the re-rendering of child components with up-to-date prop values.
Usage:
State is best used for data specific to a component that doesn't need to be shared with other components.
Props are used to send data and behavior from parent to child components, making them reusable.
Potential applications of state and props
Let's now see where these two tools of React - state and props, can be applied differently. Starting with state: it manages form inputs, meaning it keeps and updates user inputs in form fields.
State can toggle UI elements. It controls the visibility or display of certain components or sections and stores component-specific data such as a counter value or a selected item.
You can also use state to manage API responses. It can store API fetched data and trigger re-rendering when the data is received or updated.
Last but not least, state can determine which components or elements to render based on certain conditions or flags. It helps in conditional rendering.
Moving onto props: Props are generally used to provide data from a parent to child components. Props also play a key role in shaping the behavior or appearance of a component, enabling it to be reused with diverse settings.
Props can assist in sharing data between siblings unconnected via parent-child relation. They pass down callback functions from parents to children, enriching interaction and communication among components.
Remember, these instances are not limited and both state and props can work together for building complex, interactive React applications.
Conclusion
To wrap up, state is used in React for managing mutable data inside a component. In contrast, props pass read-only data from parent components to child ones. Understanding their differences aids in creating reusable React components. In this topic, you have reviewed their key differences and uses.
Read more on this topic in The Importance of Using Unique Keys in React on Hyperskill Blog.