Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react – the prop value remain unchanged after parents update corresponding state

There are 2 components in my Application, which are Button and Input
enter image description here

After I click Click to update state button, the value of input with value May should be changed to May New, but I find that it doesn’t happen.

When I check the Input component, the useEffect does not fire.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function Input({ inputValue }) {
  // the useEffect does not fire
  useEffect(() => {
    console.log(inputValue);
  }, [inputValue]);
  ...
}

How can I solve it?

App.js

import "./styles.css";

import React, { useState } from "react";

import Input from "./Input";
import Button from "./Button";

export default function App() {
  const [people, setPeople] = useState([
    {
      id: 0,
      name: "May"
    },
    {
      id: 1,
      name: "John"
    }
  ]);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {people.map((pp) => {
        return <Input key={pp.id} inputValue={pp} />;
      })}
      <Button people={people} setPeople={setPeople} />
    </div>
  );
}

Button.js

import React from "react";

function Button({ people, setPeople }) {
  return (
    <button
      onClick={() => {
        let peopleTemp = people;
        peopleTemp[0]["name"] = "May New";
        setPeople(people);
      }}
    >
      Click to update state
    </button>
  );
}

export default Button;

Input.js

import React, { useEffect } from "react";

function Input({ inputValue }) {
  useEffect(() => {
    console.log(inputValue);
  }, [inputValue]);

  return <input readOnly defaultValue={inputValue.name} />;
}

export default Input;

Codesandbox
https://codesandbox.io/s/wizardly-liskov-k8kxin?file=/src/Button.js

>Solution :

That is because you are mutating the state.

use

onClick = {() => {
    const updatedPeople = people.map((person, index) => {
      // here you check if the person is the one you want to update
      if (index === 0) {
        return { ...person,
          name: 'May New'
        };
      }
      return person;
    })
    setPeople(updatedPeople);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading