How to Update Props in React
In React, properties (props) are read-only and cannot be modified directly by the component that receives them. This article explains how to change the data passed via props by managing state in a parent component and using callback functions to trigger updates, adhering to React’s unidirectional data flow.
The Rule of Immutability
React props are immutable. Once a child component receives props from
its parent, it cannot mutate them. Attempting to reassign a prop (e.g.,
props.value = "new value") will result in an error or
unexpected behavior because React relies on pure components that do not
modify their inputs.
To “update” a prop, you must update the state of the parent component that provides that prop. When the parent’s state changes, it triggers a re-render, passing the new state down as updated props to the child component.
Step-by-Step: How to Update Props
To update props in a child component, you must follow these three steps:
- Define State in the Parent: Keep the data you want
to change in the parent component’s state using the
useStatehook. - Pass State as Props: Pass the state value down to the child component as a prop.
- Pass an Updater Function: Pass a function from the parent to the child that allows the child to request a state change.
Code Example
Here is a practical example demonstrating this pattern:
import React, { useState } from 'react';
// Parent Component
function Parent() {
const [message, setMessage] = useState("Hello World");
const updateMessage = () => {
setMessage("Hello React!");
};
return (
<div>
{/* Passing the state and the updater function as props */}
<Child text={message} onButtonClick={updateMessage} />
</div>
);
}
// Child Component
function Child(props) {
return (
<div>
<p>{props.text}</p>
{/* Triggering the parent's function on click */}
<button onClick={props.onButtonClick}>Update Text</button>
</div>
);
}
export default Parent;How It Works
- The
Parentcomponent initializes amessagestate with"Hello World". - The
Parentrenders theChildcomponent, passing themessagestate as thetextprop, and theupdateMessagefunction as theonButtonClickprop. - When the user clicks the button in the
Childcomponent, it invokesprops.onButtonClick(). - This executes
updateMessagein theParentcomponent, which callssetMessage("Hello React!"). - The
Parentstate updates, causing theParentto re-render. - The
Childcomponent re-renders with the newtextprop value:"Hello React!".