Shamaayil Ahmed

Shamaayil Ahmed

React Hook #1 useState()

React Hook #1 useState()

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

React Hooks are v16.8 specification which allows certain backward compactible functionalities without any use of class based ordering.

States in React Component

As components are the building block of the entire application, they are provided with a built-in object to store property values known as states.

So as to preserve the state value after the final render, we use the function based chunks called useState (one of the basic react hook).

Preserve state value

So as for consistent and updated state value across the component throughout the lifecycle, the is a need to preserve the state value

Class based chunk

useState() functionality may seem silly, but you won't regret using them compared to class based chunk used before.

/*dynamically render the input value*/

import React from 'react';

export default class Greeting extends React.Component(){
   constructor(props){
      super(props);
      this.state={
         name:'Mary',
      }
      this.handleChange=this.handleChange.bind(this);
   }

   handleChange(e){
      this.setState({
         name: e.target.value
      });
   }

   render(){
      return <input value={this.state.name} onChange={this.handleChange} />
   }
}

So as for a compact code we come across useState() which re-renders after any change in state value.

Hook based chunk (useState)

Import useState function from react.

import React,{ useState } from 'react';

export default class Greeting extends React.Component(){
   const [name,setName] = useState('Mary');
   /*name is the state variable and setName has the power to change the value of name and Mary is the initiall value for name*/

   function handleChange(e){
         setName(e.target.value);
   }

   return <input value={name} onChange={handleChange} />
}

Basic Implementation

Let's see a birthday reminder list, as for the working of useState().

App component which renders the List component.

import React, { useState } from 'react';
import data from './data';            /*an array of object*/
import List from './List';               /*actual list with provided data*/
function App() {
  const [people, setPeople] = useState(data);
  return <main>
    <section className="container">
      <h3>{people.length} BirthDays Today</h3>
      <List people={people} />         /*de-structure the objects fields*/
      <button onClick={() => setPeople([])}>Clear</button>
    </section>
  </main>;
}

export default App;

List component which manipulates the birthday list.

import React from 'react';

const List = ({ people }) => {      /*de-structure the people data fields*/ 
  return (
    <>                                                 /*react fragment */
      {people.map((person) => {          /*map each field and manipulate the profile*/
        const { id, name, age, image } = person;
        return <article className="person">
          <img src={image} alt="" />
          <div>
            <h4>{name}</h4>
            <p>{age} years</p>
          </div>
        </article>
      })}
    </>
  );
};

export default List;

Major takeaway

A useState is a hook, a hook is a function provided by React that lets to hook to react features from function component

Watch React CONF 2018 for further explanations.


Hope you all liked the post, share your impressions and queries below <3

 
Share this