React State Events Handling — 2

React State Events Handling — 2

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article
This article is sponsored by Flutterwave - Flutterwave is the easiest way to make and accept payments both online and offline from customers anywhere in the world. It is absolutely free!

In the previous article, we saw how a class-based function uses a state property to hold the current Person object values but gets overridden by the setState method upon a click of the button. That is, the state property object gets updated to the setState method objects upon a click.

Below was how the code looked like:

Person/Person.js

import React from 'react';
import { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ]
  };

  personHandler = () => {
    this.setState({
      persons: [
        { name: 'Andela', language: 'Ember', id: '2sdr3' },
        { name: 'John', language: 'Backbone', id: 'de6c3' },
        { name: 'Mary', language: 'Angular', id: 'c1z3x' }
      ]
    })
  };

  render() {
    return (
      <div>
        <Person
          name={this.state.persons[0].name}
          language={this.state.persons[0].language}
          id={this.state.persons[0].id} />
        <Person
          name={this.state.persons[1].name}
          language={this.state.persons[1].language}
          id={this.state.persons[1].id} />
        <Person
          name={this.state.persons[2].name}
          language={this.state.persons[2].language}
          id={this.state.persons[2].id} />
        <button 
          onClick={this.personHandler}>Change Person State</button>
      </div>
    );
  }
}

export default App;

The PersonHandler is just a function call that gets executed whenever there's a click on the button.


React Hooks

Classed-based components in the past were the only way to manage the state property, but there is now a new approach to manage it. With a new feature in React 16.8 called, React hooks you can now manage components in a functional component.

React Hooks is the collection of functions that you can use in functional components.

The useState is the most important React Hook. Importing useState (not Component) from the React library, you manage state in a functional component successfully. TheuseState is an object that holds the initial (current) values or data of a component. The second state will be a function that allows state updates in the functional component.

In the example below, array destructuring is used to hold the current state values and final state values.

See the example below:

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

const App = () => {
  const [initialPersonState, finalPersonState] = useState({
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ]
  })

  const personHandler = () => {
    finalPersonState({
      persons: [
        { name: 'Andela', language: 'Ember', id: '2sdr3' },
        { name: 'John', language: 'Backbone', id: 'de6c3' },
        { name: 'Mary', language: 'Angular', id: 'c1z3x' }
      ],
    })
  };

  return (
    <div>
      <Person
        name={initialPersonState.persons[0].name}
        language={initialPersonState.persons[0].language}
        id={initialPersonState.persons[0].id} />
      <Person
        name={initialPersonState.persons[1].name}
        language={initialPersonState.persons[1].language}
        id={initialPersonState.persons[1].id} />
      <Person
        name={initialPersonState.persons[2].name}
        language={initialPersonState.persons[2].language}
        id={initialPersonState.persons[2].id} />
      <button
        onClick={personHandler}>Change Person State</button>
    </div>
  );
};

export default App;

Although I prefer to use state and setState as conventional names array elements if it is only one React hook or useState method in the functional component.

In the code above replace the initialPersonState and finalPersonState everywhere in the Person/Person.js file to state and setState:

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

const App = () => {
  const [state, setState] = useState({
    persons: [
      { name: 'Bello', language: 'React', id: '2sdr3' },
      { name: 'Michael', language: 'Vue', id: 'de6c3' },
      { name: 'Mary', language: 'Angular', id: 'c1z3x' }
    ]
  });

  const personHandler = () => {
    setState({
      persons: [
        { name: 'Andela', language: 'Ember', id: '2sdr3' },
        { name: 'John', language: 'Backbone', id: 'de6c3' },
        { name: 'Mary', language: 'Angular', id: 'c1z3x' }
      ],
    })
  };

  return (
    <div>
      <Person
        name={state.persons[0].name}
        language={state.persons[0].language}
        id={state.persons[0].id} />
      <Person
        name={state.persons[1].name}
        language={state.persons[1].language}
        id={state.persons[1].id} />
      <Person
        name={state.persons[2].name}
        language={state.persons[2].language}
        id={state.persons[2].id} />
      <button
        onClick={personHandler}>Change Person State</button>
    </div>
  );
};

export default App;

Note

  • The UseState returns an array of exactly two elements, the initial state, and the final state. The element's name can be named anything but descriptive.

  • You can have multiple useState calls in React hooks.

This just an eye-opener of React Hooks. It will be explained further later in a separate article.

Happy Coding!!!


Buy me a Coffee


Techstack | Flutterwave

Techstack article, sponsored by Flutterwave. Flutterwave is the easiest way to make and accept payments both online and offline from customers anywhere in the world. It is absolutely free! Also, you get a Flutterwave dollar barter card when you signup. Open an online store and take your business anywhere in the world.

Sign up today to get started

Support what I do and push me to keep making free content.

 
Share this

Impressum

TechStack Media was launched in the year 2020 to make the learning of web technologies easier and more fun.

My name is Bello Osagie, I am the founder of TechStack, and my focus is to give in-depth, senior-level knowledge of the course through a step-by-step approach. You will learn HTML, CSS, JavaScript etc.

You can find my posts on Dev.to, Medium, Hashnode, Hackernoon, and Blogspot

The approach is to first start with the basics, then advance to more topics. Lots of practical examples are added to make learning more easier. TechStack Media also includes videos apart from content writing to make sure you understand all the concepts in a particular topic or course. Contents are frequently updated, so you do not miss out on the latest technology.

If you need a contact me on any of my social media or email:

For exclusive web technology tutorials, join my patron page.

Proudly part of