DEV Community

SATHISHKUMAR R
SATHISHKUMAR R

Posted on

What is useState?

useState is a React Hook used to store and update data in a component.

For example:

  • Counter value
  • Username
  • Login status
  • Shopping cart items.
  1. Basic syntax:

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

  • state — current value.
  • setState — function to update the value.
  • useState(initialValue) — sets the starting value.
  1. Example: Counter app:

import { useState } from "react";

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

return (


Count: {count}

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

);
}

export default App;

How it works:

  1. useState(0) sets the initial count to 0.
  2. count stores the current number.
  3. When you click Increase, setCount(count + 1) updates the number.
  4. React re-renders the component to show the new value.

  5. Example:
    Change a name

import { useState } from "react";

function App() {
const [name, setName] = useState("Sathish");

return (


Hello, {name}!


setName("Kumar")}>
Change Name


);
}

export default App;

Before clicking: Hello, Sathish!

After clicking: Hello, Kumar!

  1. Important points:
  • Import useState from React.
  • Call it at the top level of your component.
  • Don't directly modify the state variable. Use its setter function.
  • useState can store numbers, strings, booleans, arrays, and objects.

Top comments (0)