This.State Vs UseState Hook

Manage State Variables In React... This.State Vs UseState Hook

  • March 26, 2020
  • by Megha Dhawan
  • Web Development

In my earlier articles, I had covered two things:-

  1. How to create Functional (stateless) components and Class-based components
  2. Why we use "useState" Hook

Now, posting something more on these related to state variables. 

WHAT ARE STATE VARIABLES?

Normally, variables “disappear” when the function/block exits but state variables are preserved by React.

HOW TO MANAGE STATE IN ANY COMPONENT EITHER FUNCTIONAL(STATELESS) OR CLASS-BASED?

Mostly we do a mistake when we learn from any source how to preserve the values in React i.e. set the state variable in your component.

We have two methods to set the state variable in your component. The two ways are:-

  1. this.state
  2. useState Hook

MISTAKE:  We now try to use anyone method from the two above listed to maintain state without having the knowledge that their use is depended on the type of react component.

SO, FROM NOW LET'S CORRECT OUR MISTAKE.

Declaring a State Variable

1) Class-based component -

In a class, this.state is used to manage state but hooks not works.

We initialize the count state to 0 by setting this.state to { count: 0 } in the constructor:

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

2) Functional (stateless) components -

In a function, useState hook is used to manage state but this.state not works as we have no "this", so we can’t assign or read this.state.

We call the useState Hook directly inside our component:

import React, { useState } from 'react';

function Example() {    // Declare a new state variable, which we'll call "count"

const [count, setCount] = useState(0);