In this article, we will see how to update the state on the button click in reactJS.

We use the useState hook to manage the state in reactJS. useState hook returns the state variable and a callback function to update the state variable.

import React, { useState } from 'react';

Declare the state variable the update function

To update the state variable on the button click, we need to declare the state variable and its update function outside of the event handler. By using the useState hook, we declare the state variable and its update function.

const [count, setCount] = useState(0);

Update the state inside the event handler

We have declared the state variable and update function, now we can call the hook inside the event handler to update the state in response to user interactions.

For example, if we want to update the ‘count‘ state variable when a button is clicked, we can do the following:

function handleClick() {
  setCount(count + 1);
}

return (
  <div>
    <p>You clicked {count} times</p>
    <button onClick={handleClick}>Click me</button>
  </div>
);

In the above example, we declared an event handler called ‘handleClick‘ which will be called when the button is clicked. Inside the event handler, we are calling the ‘setCount‘ function to update the value of ‘count‘ by adding 1 to its current value.

The current value of the count will be rendered inside the paragraph tag and a button that calls the handleClick function when clicked.

Categorized in:

Tagged in: