useState() Hook in ReactJS

Let’s continue with state & props article.

  • We can manage state in Functional Components with React Hooks.
  • React Hooks are a collection of functions which you can use in Functional Components.
  • useState() REPLACE the content of the original state unlike setState() that MERGE the content to the original state.
  • useState() returns an array with two elements, always. We need to store the result of it in an array constant.
  • The first element of the array that we get back is always be the current state, so initially that object and whenever we change it, then the updated state.
  • The second element is a function that allows us to update this state.
  • We can use Array Destructuring to store these two elements that useState() will return.
  • this.state only exist in class-based components. Hence, we have to replace this.state with the first element of the array.
  • As we can have functions inside functions in React as well as in JavaScript, we can create event handlers within functional components.
  • You can use multiple useState() for multiple states rather than managing all states in one useState().

we will not make any changes in Person.js class

Replace the code in App.js file with the below code:

import React, {useState} from 'react';
import Person from './Person/Person';

const App = props => {
  const [personState, setPersonState] = useState({
      person:[
        {name: "Paul", location: "New York"},
        {name: "David", location: "Atlanta"},
        {name: "Raj", location: "London"}
      ],
      otherDetails: "I am working as Software Developer"
  });

  const buttonClickHandler = () => {
    setPersonState({
      person:[
        {name: "Duke", location: "New York"},
        {name: "David", location: "Atlanta"},
        {name: "Raj", location: "Delhi"},
      ],
      otherDetails:personState.otherDetails
    });
  };

  return (
    <div>
      <Person name={personState.person[0].name} location={personState.person[0].location} />
      <Person name={personState.person[1].name} location={personState.person[1].location} >{personState.otherDetails}</Person>
      <Person name={personState.person[2].name} location={personState.person[2].location} />
      <button onClick={buttonClickHandler} >Click Me</button>
    </div>
  );
} 
export default App;

Below is the output before clicking the button:

Below is the output after clicking the button

You can see that “I am working as Software Developer” statement is gone after clicking the button. This is because of useState() hook as it REPLACES the old state with the new state. If you want all states to be included, you have to manually make sure to include other states.

Below line of code make sure to include the original data of the state.

 

 

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started