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:

  1. Define State in the Parent: Keep the data you want to change in the parent component’s state using the useState hook.
  2. Pass State as Props: Pass the state value down to the child component as a prop.
  3. 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

  1. The Parent component initializes a message state with "Hello World".
  2. The Parent renders the Child component, passing the message state as the text prop, and the updateMessage function as the onButtonClick prop.
  3. When the user clicks the button in the Child component, it invokes props.onButtonClick().
  4. This executes updateMessage in the Parent component, which calls setMessage("Hello React!").
  5. The Parent state updates, causing the Parent to re-render.
  6. The Child component re-renders with the new text prop value: "Hello React!".