SmartCodingTips

🧠 Understanding React State

State is a built-in object in React components used to store dynamic data that affects how a component renders and behaves. It’s the β€œbrain” of interactive UI components.


βš™οΈ What is useState?

In functional components, you use the useState() hook to declare state.

Example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Here, count is a state variable. setCount is the function used to update it.

πŸ“Œ Rules of Using State

  • You must import useState from react.
  • useState returns an array: [value, setter]
  • You cannot directly modify the state (use the setter function).
  • Setting state re-renders the component.

🧩 Multiple State Variables

function Profile() {
  const [name, setName] = useState("Sangram");
  const [age, setAge] = useState(25);

  return <p>{name} is {age} years old</p>;
}

You can use multiple useState hooks for different pieces of state.

βœ… Best Practices

  • Initialize state with a sensible default.
  • Use one state per concern instead of nesting complex objects.
  • Keep derived values outside of state.
  • Update state immutably (e.g., don’t directly mutate arrays/objects).