DEV Community

Sajin Joe J
Sajin Joe J

Posted on

React useState Hook

useState is a React Hook used to store and update data in a component. When the state changes, React updates the UI.

1. Basic syntax

const [value, setValue] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

value — current state value.
setValue — function to update the state.
useState(initialValue) — sets the initial value.

2. Example: Counter

import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>{count}</h1>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      <button onClick={() => setCount(count - 1)}>
        Decrement
      </button>

      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

How it works:

  1. useState(0) sets the initial count to 0.
  2. setCount(count + 1) increases the count.
  3. setCount(count - 1) decreases the count.
  4. setCount(0) resets it to zero.

Top comments (0)