Ad Code

Responsive Advertisement

🔥 Introduction to React Hook - useState

 

📌 What is useState?



useState
is a React hook that lets you add state to functional components. It allows a component to "remember" values between renders.


🔹 Basic Syntax

import { useState } from "react";
function Counter() {
  const [count, setCount] = useState(0); // Declare state variable
 return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}
export default Counter;

🛠 How It Works:

  • useState(0)Initializes state (count) with 0.
  • setCount(count + 1) Updates state when the button is clicked.
  • Component re-renders with the new state.


🔹 useState with Objects

import { useState } from "react";
function UserInfo() {
  const [user, setUser] = useState({ name: "John", age: 25 });
  return (
    <div>
      <h2>Name: {user.name}</h2>
      <h2>Age: {user.age}</h2>
      <button onClick={() => setUser({ ...user, age: user.age + 1 })}>
        Increase Age
      </button>
    </div>
  );
}
export default UserInfo;

📌 Key Points:
  • When updating objects, always spread the previous state (...user) to avoid losing data.


🔹 useState with Arrays

import { useState } from "react";
function TodoList() {
const [tasks, setTasks] = useState(["Buy milk", "Go to gym"]);
return (
 <div>
    <ul>
        {tasks.map((task, index) => (
          <li key={index}>{task}</li>
        ))}
     </ul>
      <button onClick={() => setTasks([...tasks, "New Task"])}>Add Task</button>
    </div>
  );
}
export default TodoList;

📌 Key Points:

  • Use map() to render arrays.
  • Always spread the existing array (...tasks) when updating.




Post a Comment

0 Comments