useState in ReactJS — Simple Example

Abhay Singh
2 min readAug 17, 2022

Hi all! This is my first story on Medium. I’ll make it simple to explain.

Intro: Hooks got introduced in React 16.8. We have useState, useEffect, useLayoutEffect, useReduce etc. , in this article we’ll see useState, it’s easy😁.

Purpose: It makes our job easy when it comes to store our state variable and update it dynamically. State variable are those variable which store value from our current context(you can say situations for easy understanding). We can use hooks and make our life easier. We’ll see the example now.

Usage:

import React, { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
⭐ [count, setCount] = useState(0);
return (
<div>
👍 <p>You clicked {count} times</p>
👌 <button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Explanation:

We are declaring the State variable as count, setCount will be used when we update the count variable (we’ll see it). The value inside the useState is the initial value for e.g: var count = 0 ; , so when the code runs for the first time, count will have 0 as its initial value.

👍Here we are simply using the count variable in our HTML code. Always remember to put the JavaScript code inside the curly braces. It helps evaluating the JavaScript expression while compilation. A JavaScript expression can be a variable, function, an object etc.

👌This expression onClick={() => setCount(count + 1)} looks self explanatory. On button click we want to update the count variable to increase it’s value by 1. As you can see setCount comes to our rescue when we needed to update the count.

And that’s it ! Hope I have made this clear for you. Please clap and follow to learn good stuff easily.

--

--

Abhay Singh

I am ordinary guy with hunger of knowledge. I am currently into Information Technologies and learning to be good developer. Beside I love all sort of stuff.