Nearby lessons
16 of 43⚛️ ReactJS – useState Hook
📌 What is useState Hook?
The useState Hook is a special function in React that allows
us to track state in functional components.
State generally refers to data or properties that need
to be tracked in an application. With useState, we can
create and update these values easily.
� Importing useState
- Import
useStatefrom React at the top of your file - It is a named export, so we use destructuring
- Syntax:
import { useState } from 'react';
⚙️ Initializing State :
We initialize our state by calling useState() inside the function component.
useState accepts an initial value and returns two items:
- The current state value
- A function to update that state
⚙️ What can State hold :
The useState Hook can be used to keep track of strings, numbers, Booleans, arrays, object and any combination of these!
🧩 Update Objects with useState
When we update state that holds an object, the entire object is replaced.
To update only one property, use the spread operator (...) and merge it with the previous state.
Spread Operator : The JavaScript spread operator (…) allows us to quickly copy all or part of an existing array or object into another array or object.
1. Update Entire Object
2. Update Only One Property
📋 useState with Arrays
We can also manage arrays with useState.
Use the spread operator [...arr] to add or update items.
❌ Without useState vs ✅ With useState
If we update a variable directly, React will not re-render the UI.
Using useState ensures reactivity and UI updates.