useState Hook

State allows React components to change their output over time in response to user actions, network responses, and anything else. The useState hook is a special function that lets you add React state to functional components.

Syntax

When you call `useState`, it returns an array with two values: the current state and a function that updates it.

JavaScript

const [state, setState] = useState(initialValue);

Counter Example

Let's build a simple counter where the value increases when you click a button.

JavaScript

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

How it works

Note: Hooks must be called at the top level of your component. You cannot call them inside loops, conditions, or nested functions.