ReactJS – useState hook


In this article, we are going to see how to use the useState hook in a functional component.

State is the place where the data comes from. We should always try to make our state as simple as possible. With React 16.8, hooks are released which allow us to handle the state with less coding.

Syntax

const [state, setState] = useState(initialstate)

It accepts two parameters – state and setState. State is the current state, while setState is used to change the state of the functional component.

On every state change, the component re-renders with the updated state.

Example

In this example, we will build a React application that changes the state of a functional component when a button is clicked and also re-renders it.

App.jsx

import React, { useState } from 'react';

function App() {

   const [click, setClick] = useState(0);
   return (
      <div>
         <p>Button clicked {click} times</p>
         <button onClick={() => setClick((prev)=> prev + 1)}>Click me</button>
      </div>
   );
}
export default App;

In the above example, the state of the object can be changed in two ways −

  • setClick((prev)=>prev + 1)}

  • setClick(click + 1)}

In the second option, the state is updated by incrementing the value by 1, but this doesn’t ensure that the 1 is added to the previous updated state. In the first option, it is ensured that 1 is added to the previous updated state’s value only.

Output

This will produce the following result.

Updated on: 19-Mar-2021

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements