Nearby lessons

7 of 44

📦 ReactJS – State

📌 What is State?

📌 What is State in React?

State is a built-in object that allows components to **store and manage data** that can change over time.

📌 Key Points About State

  • State is **mutable**, meaning it can be changed by the component.
  • State allows React components to remember data between renders.
  • State is managed **inside the component**.
  • State changes trigger **re-rendering** of the component.
  • In functional components, state is used with the useState hook.

⚙️ Using useState Hook

The useState hook is used to declare state variables in functional components.
React Playground
import React, { useState } from 'react';

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

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

🔄 Updating State

You can update state using the setter function returned by useState.

Every time state changes, React re-renders the component automatically.

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

export default function App() {
  const [text, setText] = useState("Hello");

  return (
    <div>
      <h1>{text}</h1>
      <button onClick={() => setText("Hello World!")}>Change Text</button>
    </div>
  );
}

👶 Using State with Multiple Components

State can be used in multiple components independently.

Each component manages its own state using useState hook.

React Playground
import React from 'react';
import Counter from './Counter.jsx';

export default function App() {
  return (
    <div>
      <Counter />
      <Counter />
    </div>
  );
}

🔗 Props vs State

Props and State are both used to store data in React, but they have key differences:

  • Props: Passed from parent to child, immutable, used for communication.
  • State: Managed inside the component, mutable, used for data that can change over time.

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - Destructuring