Skip to main content

how to use useState hook in react with example

· 2 min read
Parth Maheta

Imagine a Shape-Shifting Toy

Remember those sticky toys that changed shape when you pulled or squeezed them? React's useState hook is like that for your app's data! It lets you easily update information, making your app dynamic and interactive.

What is useState?

  • A special function that helps manage the state of React components.
  • State: Information that affects how a component looks and behaves.

How it Works

Example: Counter App

  1. Declare state:
import React, { useState } from 'react';

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

const handleIncrement = () => {
setCount(count + 1); // Add 1 to count
}


return (
<div>
<p>Current count: {count}</p>
<button onClick={handleIncrement}>Increase</button>
</div>
);

}

Benefits

  • Simpler code: Organizes component logic and state management.
  • Reusable: Use useState in any component and share state.
  • Flexible: Works with various data types (numbers, strings, objects, arrays).

Tips for Beginners

  • Start with simple state changes (numbers, booleans).
  • Use descriptive names for state variables.
  • Always update state within the function provided by useState.
  • Don't modify state directly!

Further Exploration

I hope this makes useState clearer and shows its magic for making dynamic React apps! Have fun exploring.