React by Patrik

React useState Example

To use useState, you must first import it from the React library. Then you can call the useState function with an initial value for your state variable. This will return an array with two elements: the current value of the state variable and a function that you can use to update that value.

For example, let's say you want to create a counter that increments each time a button is clicked. You could use useState to create a state variable for the count like this:

import React, { useState } from 'react';

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

  const handleClick = () => {
    setCount(count + 1);

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

In this example, we're using the useState hook to create a state variable called count, which is initially set to 0. We're also defining a function called handleClick that updates the count variable by calling the setCount function with the new value of count + 1. Finally, we're rendering the current value of count in a paragraph tag, along with a button that calls the handleClick function when clicked.


Leave a Comment

All fields are required. Your email address will not be published.