Skip to content

What is useState Hook in React with Example

useState Hooks

In Todays article we are going learn about react useState() hooks with counter example. I know counter is very simple example but you will easily understand with this example. Everyone are starting with this example only :).

What is useState?

React useState() is a built in hooks or function which comes with React library. When you want to use “useState” you need to first import in your application using following code sample.

import { useState } from "react";

useState() only work with functional components. This will not work with Class components in React.

useState() returns a pair of values. The first parameter of the array is the value of the current state. The second parameter is the function that you can use to update the state value.

Now we know what the useState Hook does, let start and understand with the counter example

import React, { useState } from 'react';
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [counter, setCounter] = useState(0);

We declare a state variable called counter and set it to default 0. React remembers its current value between renders and provides our function with the latest and updated one. If we want to update the current counter, we can call setCounter.

When we want to display the current counter in a function we read directly { counter }

<p>You clicked {counter} times</p>

Counter Full Example Code

import React, { useState } from 'react';

function Example() {
    const [counter, setCounter] = useState(0);
    return (
    <div>
        <p>You clicked {counter} times</p>
        <button onClick={()=> setCount(counter + 1)}>
            Click me
        </button>
    </div>
    );
}

We import React useState hook. It allows us to persist local state in a functional component.

Inside the example component, we declare a new state variable by calling the useState hook. It returns a pair of values ​​that we name. We call our variable count because it contains the number of button clicks.

We initialize it to zero by passing 0 as the only useState argument. The second item returned is itself a function. It allows us to update the counter, so let’s call it setCounter.

When the user clicks, we call setCount with a new value. React then re-renders the sample component and passes it the new count.

Others ReactJs Hooks

Conclusion

At a first look it may be little hard to understand. Don’t rush it! If you’re lost in the explanation, look at the code above again and try to read it from start to end and also try to run program on your computer. I promise if you do this you don’t forget about react useState() hook. Must try it.