DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

useState in react

What is useState : useState is a hook that helps to add and manage state in a functional component. This helps to create a state variable by initialising it with some data and also give access to setter function which helps to update the state.

Syntax:
const [state, setState] = useState(initialValue);
where state defines the current value,
setState defines a function to update the value,
initialvalue defines the value of the state which could be an array, an object etc.

Ex:const [name, setName] = useState("Vidhya");
const [items, setItems] = useState([]);
const [user, setUser] = useState({ name: "John", age: 25 });

Ex: Counter application

import { useState } from "react";

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

  const Increase = () => setCount(count + 1);
  const Decrease = () => setCount(count - 1);
  const Reset = () => setCount(12);
return (
    <div className="flex justify-center items-center">
      <div className="bg-white shadow-lg border rounded-xl p-6 text-center w-80">
        <h1 className="text-2xl font-bold mb-4">React Counter</h1>
        <h2 className="text-3xl font-semibold mb-6">{count}</h2>

        <div className="flex gap-4 justify-center">
          <button
            onClick={Increase}
            className="px-4 py-2 bg-white border rounded-lg shadow"
          >
            Increase
          </button>
          <button
            onClick={Decrease}
            className="px-4 py-2 bg-white border rounded-lg shadow"
          >
            Decrease
          </button>
          <button
            onClick={Reset}
            className="px-4 py-2 bg-white border rounded-lg shadow"
          >
            Reset
          </button>
        </div>
      </div>
    </div>
);
}

Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)