April 5, 2024

What is State

In React, state is a built-in object that allows components to store and manage data that can change over time. It helps React know when to re-render a component when something has changed.


🔹 What is State?

State is:

  • A JavaScript object used to store dynamic information.
  • Private and controlled by the component (unlike props which are passed in from the parent).
  • Triggers a re-render when it updates.

🧱 Basic Example:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  • count is the state value.
  • setCount is the function to update the state.
  • useState(0) initializes count to 0.

⚙️ Common Features of State:

FeatureDescription
Initial stateSet using useState(initialValue)
Update stateCall the update function (e.g., setCount)
Triggers re-renderReact automatically updates the UI
Local to componentEach component manages its own state

🧠 Multiple State Variables:

const [name, setName] = useState("Jigang");
const [age, setAge] = useState(30);

You can have multiple independent state variables inside a single component.


🔄 Updating State (Important!)

  1. Don’t mutate state directly:
    count++
    setCount(count + 1)
  2. React may batch updates, so don’t rely on the current state when updating multiple times in a row. Use a function form when needed:
setCount(prev => prev + 1);

🧠 Summary:

TermMeaning
useStateReact Hook to add state to a function component
StateData that changes over time
setStateFunction to update state and re-render component