UseState

 1 Use State while using in object should be approached like this;

    export default function App() { 
  const [greeting, setGreeting] = useState({ greet: "Hello, World" }); 
  console.log(greeting, setGreeting); 
 
  function updateGreeting() { 
    const newGreeting = {...greeting}; 
    newGreeting.greet = "Hello, World-Wide Web"
    setGreeting(newGreeting); 
  } 
 Here, the newGreeting takes all the previous objects then manipulates the greet so that only greet is modified and not other object.

2 Another way is using prevState;
export default function App() { 
  const [greeting, setGreeting] = useState( 
    { 
        greet: "Hello"
        place: "World" 
    } 
  ); 
  console.log(greeting, setGreeting); 
 
  function updateGreeting() { 
    setGreeting(prevState => { 
        return {...prevState, place: "World-Wide Web"
    }); 
  } 
 Here instead of calling another constant to add the prev states we use an arrow function to add the prev states and update the object.


Comments