DEV Community

Cover image for Learn useState() in 5minutes
Minhazur Rahman Ratul
Minhazur Rahman Ratul

Posted on • Edited on

Learn useState() in 5minutes

This is one of the most used React hook. By reading this post, you will be able to use it properly.

How to use it?

To use this hook, firstly you need to import it from React.

import React, { useState } from 'react';
Enter fullscreen mode Exit fullscreen mode

Usage

In es6, we have something called array destruturing. If you know how to destructure an array. You can use this hook very easily. Let me show you an example.

const [ data, setData ] = useState('');
Enter fullscreen mode Exit fullscreen mode

So in this array the first index is a state variable. And the second index is a function. Which has the power of changing the value of state variable. And under useState you can store any type of data which will store the value under the state variable. And you can change the value of the state variable with the function named 'setData'. You can give any name to the state variable and function.

I know you are a little bit confused. Wait let me show you a simple example.

import React, { useState } from "react";

const App = () => {
  const [data, setData] = useState("Hello world");
  return (
    <>
      {data} // now the value will be hello world and after clicking on the button, the value will be I am a web developer
      <button
        onClick={() => {
          setData("I am a web developer");
        }}
      >
        Change value
      </button>
    </>
  );
};
export default App;

Enter fullscreen mode Exit fullscreen mode

Look at the code I have written in the top. Firstly I imported React and useState from 'react'. Then I have stored 'Hello world' under a state variable named ' data '. Then I am changing the value of the state variable onclicking on the button by just calling a function which is changing the value of our state varialbe. So that's how it is working.

You can store anything under this useState. You can store a string, object, array, number, boolean whatever. Just write them under the useState. Then you can use them by just calling the state variable . Then you can also change the variable with the function.

import React, { useState } from "react";

const App = () => {
  const [data, setData] = useState({
    name: "Ratul",
    age: 16
  });
  return (
    <>
      Name is : {data.name} and age is: {data.age}
      <button
        onClick={() => {
          setData({
            name: "Jack",
            age: 21
          });
        }}
      >
        Chnage Value
      </button>
    </>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

In this code, I just stored an object under the state variable. I am rendering them in my body. And onclicking on the button I am changing values under the object. Which is stored under the state variable. I am changing them very easily by just using the state function. Easy! Now we will create a mini project.

Mini Project

Try to create a project which will have two buttons. One of the button will increment the value of 'x' and another one will decrement the value of 'x'. And the value can't be under 0. It means the lowest value will be 0. So try it yourself using useState() hook.

import React, { useState } from "react";

const App = () => {
  const [data, setData] = useState(0);
  return (
    <>
      <button
        onClick={() => {
          setData(data + 1);
        }}
      >
        Increament
      </button>
      {data}
      <button
        onClick={() => {
          setData(data - 1);
          if (data === 0) {
            setData(data);
          }
        }}
      >
        Decrement
      </button>
    </>
  );
};
export default App;

Enter fullscreen mode Exit fullscreen mode

So I first of all I created a state which has a state variable and a function. Then I have stored a number 0. Which is our initial value of our state variable. And we can update it with the function. Now our condition was one of the button will increment the value of our number. So I just called a function onclicking on the increment button. Which is just incrementing the value of our state variable by 1. And another condition was, a button which will decrement the value of our number by 1 and the value can't be less than 0. So the numbers can't be negative. So we are just decrementing the value of our state variable by 1. And putting a condition that, if the value becomes 0 it will be remain 0. It will not be changed. And that's all.

Thanks for reading that post. Hope you enjoyed that. If you found any confusion or wrong details, please let me know in the discussions. And make sure you follow me to recieve all the informational posts just like that.

:)

Top comments (7)

Collapse
 
allan2012 profile image
Allan Kibet

Simple and awesome intro

Collapse
 
morganoliveira2018 profile image
morganOliveira2018

Great explanation. Do you know what it means when you switch to useState (true)? For example: const [button, setButton] = useState (true); Could you explain me.

Collapse
 
developeratul profile image
Minhazur Rahman Ratul

You can do conditional rendering by putting a boolan value to your state variable. This video might help you. :)

Collapse
 
tamjidahmed10 profile image
TamjidAhmed10

can u do useEffect() πŸ₯ΊπŸ₯ΊπŸ₯Ί

Collapse
 
developeratul profile image
Minhazur Rahman Ratul • Edited
Collapse
 
imsikun profile image
Subhakant Mishra

This is the simplest way I have seen so far.
Thanks man
Really helps!!

Collapse
 
developeratul profile image
Minhazur Rahman Ratul

My pleasure