use object in useEffect 2nd param without having to stringify it to JSON

后端 未结 3 1735
小蘑菇
小蘑菇 2020-12-30 03:13

In JS two objects are not equals.

const a = {}, b = {};
console.log(a === b);

So I can\'t use an object in useEffect (React ho

3条回答
  •  萌比男神i
    2020-12-30 03:44

    Plain (not nested) object in dependency array

    I just want to challenge these two answers and to ask what happen if object in dependency array is not nested. If that is plain object without properties deeper then one level.

    In my opinion in that case, useEffect functionality works without any additional checks.

    I just want to write this, to learn and to explain better to myself if I'm wrong. Any suggestions, explanation is very welcome.

    Here is maybe easier to check and play with example: https://codesandbox.io/s/usehooks-bt9j5?file=/src/App.js

    const {useState, useEffect} = React;
    
    function ChildApp({ person }) {
      useEffect(() => {
        console.log("useEffect ");
      }, [person]);
    
      console.log("Child");
      return (
        

    Inside child

    {person.name}
    {person.age}
    ); } function App() { const [person, setPerson] = useState({ name: "Bobi", age: 29 }); const [car, setCar] = useState("Volvo"); function handleChange(e) { const variable = e.target.name; setPerson({ ...person, [variable]: e.target.value }); } function handleCarChange(e) { setCar(e.target.value); } return (
    Name: handleChange(e)} value={person.name} />
    Age: handleChange(e)} value={person.age} />
    Car: handleCarChange(e)} value={car} />
    ); } ReactDOM.render(, document.getElementById("root"));
    
    
    

提交回复
热议问题