React Hooks: Implementation of useState

josesrodriguez610 - Jul 13 '20 - - Dev Community

Today I’m going to write about a React Hook. Instead of going through some of them I’m going to focus on the reason and implementation of one, the useState hook.  To use this feature in your existing projects you will need to update to Node v10.8.0

Before we dive into this topic, there are two things we need to know:

1. Destructuring


One of the best feature of ES6 is destructuring. This feature is crucial if you want to develop using a front end framework such as React because useState is a function that relies on array destructuring. This is a Method of extracting multiple properties from an array by taking the structure and unpacking the elements through assignments by using a syntax that looks similar to array literals. Here is an example of array distructuring.


const [ one, two ] = [ 1, 2 ];

console.log(two); // 1
console.log(one); // 2

Enter fullscreen mode Exit fullscreen mode

2. What is a React State?


A simple answer is that React state is an object where you store property values which belong to the component and those values can change.

3. What is useState?


This hook will have the capabilities that this.state provides in a class. The difference is that unlike classes the state doesn't have to be an object, with useState we can keep a string or a number.

Now let’s focus on our main topic:


Hooks! 

Hooks are functions that let you use React features and useState is a hook that lets you add React state to function components. Before this update, the way to manage a local state in a component was to create a class.  We call Hooks function components because they have the ability to use the React State.

Why should we use Hooks like useState? 



We should use Hooks because we can re-use functionality between components which gives us an advantage editing the component and updating the component state. React is not getting rid of classes but we can finally use normal functional components to  manage the state. People are used to writing functional components and now they don’t have to convert them to classes to get all their functionality.

Back in a day if you wanted to add some state to a function component you needed to convert it to a class but now we can use a Hook and it is very easy. Here I will help you with the implementation.

We have a class component with a state, the old way!

then we will be changing it into a functional component using useState in a couple of steps:

import React, {Component} from 'react';

// 1. create a class component 
class ClassNumber extends Component {    

  constructor(props){
    super(props)

//  2. create a state variable set to 0
    this.state = { 
      number : 0 
    }                   
  }

/* 3. method capable of setting a new state value 
calling setState to set the new value */

  randomNumber = () => {              
    this.setState({
//random number to 10 
      number: (Math.floor(Math.random() * 10))
    })
  }

  render (){
  return (
    <div>
      <button onClick={this.randomNumber}> 
           Number? {this.state.number}</button>

/* the output is a button which number is set to 0 and if clicked will give you a random number */
    </div>
  )
  }
};

export default ClassNumber;
Enter fullscreen mode Exit fullscreen mode

Implementing useState

First we import our useState from React and then we make our Number a function component.

import React, {useState} from 'react';

function FuncNumber() {    

}

export default FuncNumber
Enter fullscreen mode Exit fullscreen mode

Since we have a functional component we can’t use state like before. We need a different way which will be implementing the useState Hook which is a special function that will let you add state to functional component.
The way it works is that useState is a function, so we have to call it. The function useEffect accepts an arguments which is the initial value of the state property and useState returns a pair of values which are the current state and a function that updates it.
We will use destructuring to set this function values.

import React, {useState} from 'react'

//create a function component 
function FuncNumber() {    

/* Use hook which accepts an argument of initial value, 
  returns the current value and method that updates the current value */
const [number, setNumber] = useState(0)   

}

export default FuncNumber
Enter fullscreen mode Exit fullscreen mode

The variable number and setNumber are variable names set by you but it is good practice to give them the name of variable and setVariable. Current value and the updated value.

Now we add our button and on click we will use a setNumber which will be the new number which is set to a random number and because it is a function call it will become an arrow function

import React, {useState} from 'react';

function FuncNumber() {    

  const [number, setNumber] = useState(0)   

 return (
     <div>
       <button 
             /* setNumber will update the current value to a random number */
       onClick={() => setNumber(Math.floor(Math.random() * 10))}>
          Number: {number}</button>
     </div>
   );
/* the output is a button which number is set to 0 and if clicked will give you a random number */

 }

export default FuncNumber;
Enter fullscreen mode Exit fullscreen mode

Conclusion

Hooks will let you use functions which provide more flexibility in extracting, testing and reusing code. Thanks to Hooks the complexity of state management has been reduced. With this implementation we need less code and it is very clear to read and understand.

. . . . . . . . . .