Menu

React useState Hook
πŸ“°

React useState Hook

DEV Community: reactΒ·Sajin Joe JΒ·1 day ago
#PhRfAQYW
#devtoreact#devto#dev#count#setcount
Reading 0:00
15s threshold

Sajin Joe J

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.