D DevBrainBox

React State Management

State Management

What is "State" in React?

State is a built-in object that allows components to create and manage their own data. When state changes, the component re-renders to reflect the new data in the UI.

import { useState } from 'react';

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

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Why Do We Need State Management?

  • Lifting state up becomes hard as apps grow.
  • Components need to share state.
  • Some data needs to be global (e.g., user authentication, theme).

Levels of State Management

  1. Local State (within a component)

    • Managed using useState or useReducer
    • Best for UI interactions (modals, toggles, form inputs)
  2. Shared State (between components)

    • Lift state up to a common ancestor and pass it down via props
    • Can use Context API if deeply nested
  3. Global State (accessible from anywhere)

    • Useful for app-wide data like user info, cart, theme
    • Tools: React Context API, Redux, Zustand, Jotai, Recoil
  4. Server State

    • Data from external APIs that needs caching, syncing, etc.
    • Tools: React Query, SWR

Tool - Redux

Best for - Large-scale, predictable State

Example

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable called 'count', and a function to update it: 'setCount'
  const [count, setCount] = useState(0);

  // Function to increment count
  const handleIncrement = () => {
    setCount(count + 1);
  };

  // Function to decrement count
  const handleDecrement = () => {
    setCount(count - 1);
  };

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h2>Simple Counter App</h2>
      <h3>Count: {count}</h3>
      <button onClick={handleDecrement}>-</button>
      <button onClick={handleIncrement}>+</button>
    </div>
  );
}

export default Counter;
  • useState(0) initializes count with value 0.
  • setCount updates the state.
  • When a user clicks "+" or "–", the count updates and the UI re-renders automatically.

On this page