React Update State When Props Change: Complete Solution

Photo of author

We will converse about the react update state when props change. Whenever you are using React, you may have a problem like this very often. But before moving into the topic, let us know what a prop is.

In React, a prop is something where the value of attributes of a tag is recorded. The value of props flows from the parent-to-child component. Additionally, React update state when props change can be done in three ways:  

  1. Firstly, using the useeffect hook,
  2. Secondly, determining the derived state,
  3. Finally, key props in the parent component will be implemented. 

Now that we know about props and what they do, we should know how to update React component when props change in detail.

See Also: Core Java Topics: Mastering The Fundamentals Of Java Programming

How to React Update State When Props Change

There are many ways to do this, but we will mainly focus on three ways 

  1. Firstly, by using the useeffect hookuseeffect hook
  2. Secondly, determining the Derived Statederived state in react
  3. And thirdly, implementing key props in the Parent Componentkey prop

First, we need a problem to understand its function to use these.

Problem

// items of food

let foodList = [

  { food: “🍕 Pizza”, likes: 0 },

  { food: “🍟 Fries”, likes: 0 },

  { food: “🥞 Pancakes”, likes: 0 },

  { food: “🥑 Avacado”, likes: 0 },

  { food: “🌭 Hot Dog”, likes: 0 },

  { food: “🍔 Burger”, likes: 0 },

  { food: “🥪 Sandwich”, likes: 0 },

  { food: “🌮 Taco”, likes: 0 },

  { food: “🥗 Salad”, likes: 0 },

  { food: “🧇 Waffles”, likes: 0 },

];

 

function Foods() {

  let [position, setPosition] = React.useState(0);

  

  function getNext() {

    setPosition(foodList[position+1] ? position+1 : 0);

  };

  

  return (

    <>

      <FoodItem food={foodList[position].food} likes={foodList[position].likes} />

      <div className=”text-right”>

        <button onClick={getNext} className=”my-2 px-4 py-2 border hover:bg-gray-200 rounded”>Next ➡️</button>

      </div>

    </>

  );

};

 

function FoodItem({ food, likes }) {

  const [ count, setCount ] = React.useState(likes);

  

  return (

    <div className=”rounded-lg border p-5 text-center my-2″>

      <h2 className=”my-2 text-3xl font-bold”>{food}</h2>

      <button onClick={() => setCount(count+1)} className=”my-2 px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded”>💖 x{count}</button>

    </div>

    

  );

};

When you run this code, firstly, you will see a list of food items like Pizza, Fries, Pancakes, and others. Moreover, the meter below lets you click on the foods you like. However, an issue arises when you desire a different item and proceed to the next one; the like count fails to reset. We will employ the three methods mentioned to address this to modify the React change state when props change.

See Also: Java Coding Best Practices: Write Efficient And Maintainable Code

Solution 1: By useEffect hook

Before employing this approach, it is imperative to comprehend the significance of a useEffect hook. Essentially, the useEffect hook instructs React to execute a function after rendering. It serves as a crucial element in the realm of stateful React hooks, allowing the retrieval of previous props or states within a functional component. The corresponding code for implementing this functionality is as follows:

useeffect hook

function FoodItem({ food, likes }) {

 const [ count, setCount ] = React.useState(likes);

 

 React.useEffect(() => {

   setCount(likes)

 }, [food, likes]);

 

 //…

   

 );

};

The purpose of the effect is to rerun after every render, facilitating the execution of side effects. Examining the provided code, we observe the utilization of the effect hook with the line “setcount(likes).” This signifies that each time someone modifies either “food items” or “likes,” the React update state when props change is effectively managed. Consequently, the useEffect will retrigger, restoring the likes’ value in alignment with the current food items. For instance, if you express your liking for Pizza and proceed to another food item, the count resets to zero. Yet, upon returning to Pizza, your initial like count is accurately reinstated. This exemplifies the initial method about how you can update state when props change React hooks.

Solution 2: Determine the Derived State

Derived State in React depends on other state values. There are also other states like react global state without redux in which the data is noticeable and can be replaced by other components. The code for the derived state be:

derived state in react

function Foods() {

  let [position, setPosition] = React.useState(0);

  

  function getNext() {

    setPosition((position + 1) % foodList.length); // Ensure it loops back to 0 after reaching the end

  };

  

  return (

    <>

      <FoodItem food={foodList[position]} onLike={() => increaseLikes(position)} />

      <div className=”text-right”>

        <button onClick={getNext} className=”my-2 px-4 py-2 border hover:bg-gray-200 rounded”>Next ➡️</button>

      </div>

    </>

  );

};

 

function FoodItem({ food, onLike }) {

  const { food: foodName, likes } = food;

 

  return (

    <div className=”rounded-lg border p-5 text-center my-2″>

      <h2 className=”my-2 text-3xl font-bold”>{foodName}</h2>

      <button onClick={onLike} className=”my-2 px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded”>💖 x{likes}</button>

    </div>

  );

};

 

function increaseLikes(position) {

  const updatedFoodList = […foodList];

  updatedFoodList[position].likes += 1;

  foodList = updatedFoodList;

In this code, we can see that the “Foods” component manages the food item that will be displayed, whereas the “FoodItem” component will take care of the appropriate data based on the “distance”. The “increase likes” function will update the likes based on the position of the liked item. This helps in the react update state when props change functional components.

See Also: JavaScript Vs ReactJS: A Comparative Analysis

Solution 3: Implement key prop in the ParentComponent

Implementing key props is also a great way to fix this problem. React uses a key prop to manage and update elements in a list. There are also other kinds of props that we can use, like spread props. Understanding react spread props makes things easy for you, making it easy to pass data from the parent-to-child component. But here, the key prop is the suitable solution; the code for the key prop will be:

key prop

// pass the key prop to FoodItem

function Foods() {

  let [position, setPosition] = React.useState(0);

  

  function getNext() {

    setPosition(foodList[position+1] ? position+1 : 0);

  };

  

  return (

    <>

      <FoodItem key={foodList[position].food} food={foodList[position].food} likes={foodList[position].likes} />

      <div className=”text-right”>

        <button onClick={getNext} className=”my-2 px-4 py-2 border hover:bg-gray-200 rounded”>Next ➡️</button>

      </div>

    </>

  );

};

 

// no changes here

function FoodItem({ food, likes }) {

  const [ count, setCount ] = React.useState(likes);

  

  return (

    <div className=”rounded-lg border p-5 text-center my-2″>

      <h2 className=”my-2 text-3xl font-bold”>{food}</h2>

      <button onClick={() => setCount(count+1)} className=”my-2 px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded”>💖 x{count}</button>

    </div>

    

  );

};

In this case, we will give “FoodItem” a key prop, and whenever someone changes it, the component will render again, keeping everything up to date. This is another solution for the react class component update state when props change.

See Also: React Basics: How And When To Use React Context

 FAQ

How we can update props in React?

You cannot update props because they are read-only components.

What is the alternative to useState?

You can use the useReducer hook other than useState.

How many props are too many in React?

For Instance, more than 7 props are too many in React.

Which life cycle is mandatory?

The render function lifecycle is mandatory.

Conclusion

Throughout this article, we delved into the concept of React update state when props change. When encountering this issue, there are three viable solutions at your disposal. Nevertheless, when delving into React and Redux, it is essential to discern which approach offers a strategic advantage.

A comparative analysis of React Query and Redux reveals that reducers are the optimal choice for state management. Consequently, it becomes imperative to consistently conduct evaluations, such as a “Redux vs React Query“, to ascertain the most advantageous option for your specific scenario.

Leave a Comment