Nearby lessons

16 of 44

⚛️ 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 useState from 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!

React Playground
import React, { useState } from 'react';

function UseStateHook() {
  const [name, setName] = useState("Rajesh");

  const changeState = () => {
    setName("Kumar");
  }

  return (
    <div>
      <h1>{name}</h1>
      <button onClick={changeState}>Update</button>
    </div>
  );
}

export default UseStateHook;

🧩 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

React Playground
import USWithObject from './USWithObject.jsx';
export default function App() {
  return (
    <>
      <USWithObject/>
    </>
  );
}

2. Update Only One Property

React Playground
import USWithObject from './USWithObject.jsx';
export default function App() {
  return (
    <>
      <USWithObject/>
    </>
  );
}

📋 useState with Arrays

We can also manage arrays with useState.

Use the spread operator [...arr] to add or update items.

React Playground
import USWithArray from './USWithArray.jsx';
export default function App() {
  return (
    <>
      <USWithArray/>
    </>
  );
}

❌ 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.

React Playground
import WithoutState from './WithoutState.jsx';
export default function App() {
  return (
    <>
      <WithoutState/>
    </>
  );
}

➕ Using State in Functional Components

React Playground
import WithState from './WithState.jsx';
export default function App() {
  return (
    <>
      <WithState/>
    </>
  );
}

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - useEffect Hook