State And State Management in React

What is state and state management in react? In the previous tutorial, we learn about the props as an object passing to components but the props are immutable hence once passed we cannot modify it while running the program. This is very State came in the role.

In this tutorial, we will learn about the state and state management.

Why State?

In real life or production websites, the web pages are gonna dynamic most of the time, like according to user’s interaction some components have to load and some components have to disappear from the UI.

This cannot be handled in props as props are immutable and developers hardcode the props to pass to any components to load with different properties. However, the state can handle the changes that come from users like pressing a button, hover and filling the form, etc.

These Real-Life changes are needed to handle and update the UI hence the state came in handy.

What is State?

=> A component’s state represents the mutable data that ultimately affects what is rendered on the page. The state is managed internally by the component itself and is meant to change over time, commonly due to user input (e.g., clicking a button on the page, writing a form).

To create a state object

  • We need to Define the class-based components(older)
  • Use the State property to create an object or array and passed it in the components
  • Create a folder named Components and create a file Contacts.js
  • Import React and create a component called Contact and export it.
  • Pass the props as arguments as it will handle the incoming state.
  • Render the Contact list title and map through the list of contacts send as a state from app.js.
  • Display Name and Email in a proper manner.

Contact.js

import React from 'react';

const Contact = (props) =>{
    return (
    <div className="contact">
        <h3>Contact List</h3>
        <ol className="contact-list">
            {props.contact.map((contact)=>(
                <li key={contact.id} className='contact-list-item'>
                <div classsName='contact-details'>
                <p><strong>Name:-</strong> {contact.name}</p>    
                <p><strong>Email:-</strong>{contact.handle}</p>    
                </div>  
                </li>
            ))}
        </ol>
    </div>
    )
}
export default Contact;

App.js

import React, {Component} from 'react';
import './App.css';
import Contact from './Components/Contact';


class App extends Component{
  state = {
     contacts: [
      {
        "id": "Harry",
        "name": "harry Potter",
        "handle": "harryPoter@hogwarts.com"
      },
      {
        "id": "Ron",
        "name": "Ron Wisley",
        "handle": "ronWisley@hogwarts.com"
        },
      {
        "id": "Hermoine",
        "name": "Hermoine Granger",
        "handle": "hermoineGranger@hogwarts.com"
      }
     ]
  }
  render(){
  return (
    <div className="App">
     <h2>Welcome Second</h2>
     <Contact contact={this.state.contacts}/>
    </div>
  );
}
}

export default App;

OutPut:-

Update the State

=> To make the changes in the state we cannot directly change the state as the React will not be having any idea of the changes. Therefore we use the setState option this allows us to make changes in the state and react will we know about all the changes made in the state.

There are two methods to update the state

1) Passing the setState as the function

=> The function will pass the previous as an argument and then make the changes in the new state.

This.setState((prevState) => ({

               count: prevState.count + 1

}))

2) Passing the setState as the Object

=>The object will merge with the currentState to make the new state of the component.

this.setState ({

               username: ‘DumbelDore’

})

Note:-> The function type is used when the nextState will be dependent upon the current state and the object type is used when the next state is irrelevant of the currentState.

But the End result will always be the same as the setState is called it by default re-render the entire application and changes the UI as per the changes in state

We will modify the contact list above created and try to remove contacts from it

  • In the App.js file create a function to remove contacts and take the contact as a parameter
  • Use setState as function and add currentState as parameter inside removeContact function
  • Filter the current contact and return the remaining contact list
  • Pass this function as the prop and as onDeleteContact
  • In contact.js create a button component and use the onclick attribute to trigger the property on onDeleteContact.
  • This is the way the state is changed in the react.

App.js

import React, {Component} from 'react';
import './App.css';
import Contact from './Components/Contact';


class App extends Component{
  state = {
     contacts: [
      {
        "id": "Harry",
        "name": "harry Potter",
        "handle": "harryPoter@hogwarts.com"
      },
      {
        "id": "Ron",
        "name": "Ron Wisley",
        "handle": "ronWisley@hogwarts.com"
        },
      {
        "id": "Hermoine",
        "name": "Hermoine Granger",
        "handle": "hermoineGranger@hogwarts.com"
      }
     ]
  }
removeContact = (contact) =>{
  this.setState((currentState)=>({
    contacts: currentState.contacts.filter((c)=>{
      return c.id !==contact.id
    })
  }))
}

  render(){
  return (
    <div className="App">
     <h2>Welcome Second</h2>
     <Contact contact={this.state.contacts}
     onDeleteContact={this.removeContact}
     />
    </div>
  );
}
}

export default App;

Contact.js

import React from 'react';

const Contact = (props) =>{
    return (
    <div className="contact">
        <h3>Contact List</h3>
        <ol className="contact-list">
            {props.contact.map((contact)=>(
                <li key={contact.id} className='contact-list-item'>
                <div classsName='contact-details'>
                <p><strong>Name:-</strong>{contact.name}</p>    
                <p><strong>Email:-</strong>{contact.handle}</p>    
                </div>
                <button className="contact-remove" onClick={()=>props.onDeleteContact(contact)}>
                    Remove
                </button>   
                </li>
            ))}
        </ol>
    </div>
    )
}

export default Contact;

outPut :-

After clicking the button the contact is removed from the State and the UI is reloaded