Make functional component Statefull using useState Hook


By default functional component has no state object which means that it can’t update the UI itself, responsibility to render element goes to parent component and therefore it has no render method.

Suppose you have a button component, each time the user clicking on it, you need to show a count say 1,2,3 etc. This is a Statefull components job. How this possible with functional component (stateless ), the answer is Hooks.

Hooks is a feature in Reactjs and here we have to use the useState hooks for adding a state to component which has no state.

useState

For using the hook we have to import and use the hook in our component class

import React,{useState} from 'react'

Here is our complete component class

import React,{useState} from 'react'

function HookCounter() {
const [count,setCount]= useState(0)
var count =0;
  return (
      <div>
          { <button onClick={()=>setCount(count+1)}>Count{count} </button> }          
      </div>
  )
}



export default HookCounter

In const [ variable , function]= useState(0) , the first argument to this functional list state variable, the second is a function to set the state, which is an alternative to the setState method in a Statefull component.

You need not use this keyword while using useState hook, also note that we can add a second variable to state as follows

const [name,setName]=  useState(1)

Now the UI is automatically update the change the value in the count variable, useState take care of it.

We used arrow function to handle the event , inside the function we also use the setCount.

Here is the App.js code for the complete picture of the HookCounter component.

import logo from './logo.svg';
import './App.css';
import HookCounter from './components/HookCounter'

function App() {
  return ( <div className = "App" >
{/* <Counter/> */}
<HookCounter/>
      </div>
  );
}
export default App;

I have sample project on my repo, have a look at it and earn the hook skill.

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.