useState Basics

Syntax

const [value, setValue] = useState(initialValue);
  • value: the current state.
  • setValue: function that updates the state and re-renders the component.
  • initialValue: used only on the first render.

Counter

Example

import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

Result