REACT Lesson 8 – State Basics | Dataplexa
LESSON 8

State Basics

Build interactive DataFlow dashboard components that remember and update their data using React state management.

State is like a component's memory. While props flow down from parent to child, state lives inside a component and can change over time. Think of it as a variable that React tracks — when state changes, your component re-renders automatically. The DataFlow dashboard needs interactive features. Users click buttons, filter data, and expand sections. Without state, components would be static displays. With state, they become living interfaces that respond to user actions.

What Makes State Special

Regular JavaScript variables don't trigger re-renders. You could change a variable's value, but the screen stays the same. State is different — React watches state variables and updates the DOM when they change.
// Regular variable - won't trigger re-render
function BrokenCounter() {
  let count = 0;
  
  function handleClick() {
    count = count + 1; // Changes variable but screen stays same
    console.log(count); // You'll see the number change in console
  }
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Add One</button>
    </div>
  );
}
DataFlow Dashboard

What just happened?

The button click changes the variable but the screen shows the same number. React doesn't know the component needs updating. Open browser console to see the real count increasing. Try this: Click multiple times and notice the display never changes.

The useState Hook

React provides useState to create state variables that trigger re-renders. A hook is a special React function that starts with "use" and lets you hook into React features. useState returns two things: the current state value and a function to update it. We use array destructuring to grab both.
// Import useState from React
import { useState } from 'react';

function WorkingCounter() {
  // useState returns [currentValue, updaterFunction]
  const [count, setCount] = useState(0);
  
  function handleClick() {
    setCount(count + 1); // This triggers a re-render!
  }
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Add One</button>
    </div>
  );
}
DataFlow Dashboard

What just happened?

Now the counter works! setCount tells React "this component's data changed, please re-render it." Each click updates the display instantly. Try this: Click rapidly and watch the number climb smoothly.

DataFlow Revenue Tracker

The DataFlow dashboard needs a revenue counter for the stats bar. Users want to see revenue update when new orders arrive. Here's how state makes this interactive:
function RevenueTracker() {
  const [revenue, setRevenue] = useState(42650);
  const [isUpdating, setIsUpdating] = useState(false);
  
  function simulateNewOrder() {
    setIsUpdating(true);
    // Simulate processing delay
    setTimeout(() => {
      setRevenue(revenue + 89.99);
      setIsUpdating(false);
    }, 800);
  }
  
  return (
    <div className="revenue-card">
      <h3>Total Revenue</h3>
      <p className="amount">${revenue.toLocaleString()}</p>
      <button onClick={simulateNewOrder} disabled={isUpdating}>
        {isUpdating ? 'Processing...' : 'New Order +$89.99'}
      </button>
    </div>
  );
}
DataFlow Dashboard
Notice how we use two state variables. revenue tracks the money amount. isUpdating tracks whether we're processing an order. Each has its own setter function.

State Rules You Must Follow

State has important rules. Break them and your app becomes unpredictable. Here are the core principles:

Never Mutate State Directly

Always use the setter function. Don't modify the state variable itself.

State Updates Are Asynchronous

React batches updates for performance. Don't expect immediate changes.

Only Call Hooks at Top Level

Never put useState inside loops, conditions, or nested functions.

Initialize State Properly

The initial value you pass to useState matters for the first render.

Common State Mistakes

Here's what breaks state management. The DataFlow team learned these lessons the hard way:
function BrokenUserProfile() {
  const [user, setUser] = useState({name: 'Sarah', role: 'Admin'});
  
  function updateRole() {
    // WRONG: Mutating state directly
    user.role = 'Super Admin';
    setUser(user); // React won't detect this change!
  }
  
  function fixedUpdateRole() {
    // RIGHT: Create new object
    setUser({...user, role: 'Super Admin'});
  }
  
  return (
    <div>
      <p>{user.name} - {user.role}</p>
      <button onClick={updateRole}>Broken Update</button>
      <button onClick={fixedUpdateRole}>Working Update</button>
    </div>
  );
}
DataFlow Dashboard

Critical State Concept

The broken button modifies the existing object, so React thinks nothing changed. The working button creates a new object with spread syntax ...user. React compares object references, not contents.

DataFlow Filter Toggle

Dashboard filters need to remember their on/off state. Users expect to click a filter and see it stay active until they click again. Boolean state handles this perfectly:
function DataFilter() {
  const [showHighValue, setShowHighValue] = useState(false);
  const [showRecent, setShowRecent] = useState(true);
  
  // Sample data that would be filtered
  const transactions = [
    {id: 1, amount: 1250, date: '2024-01-15', type: 'high'},
    {id: 2, amount: 89, date: '2024-01-16', type: 'normal'},
    {id: 3, amount: 2100, date: '2024-01-16', type: 'high'}
  ];
  
  return (
    <div className="filter-panel">
      <h3>Transaction Filters</h3>
      <label>
        <input 
          type="checkbox" 
          checked={showHighValue}
          onChange={(e) => setShowHighValue(e.target.checked)}
        />
        High Value Only ($1000+)
      </label>
      <label>
        <input 
          type="checkbox" 
          checked={showRecent}
          onChange={(e) => setShowRecent(e.target.checked)}
        />
        Recent (Last 7 days)
      </label>
      <p>Active filters: {showHighValue ? 'High Value ' : ''}{showRecent ? 'Recent' : ''}</p>
    </div>
  );
}
DataFlow Dashboard

What just happened?

Each checkbox has its own state variable and update function. The onChange event captures user clicks and updates state. React keeps the checkboxes in sync with the boolean values. Try this: Toggle filters and watch the active summary update instantly.

State unlocks interactivity that props alone cannot provide. While props flow data down the component tree, state lets components remember information and respond to user actions. The DataFlow dashboard comes alive when components can track clicks, filters, form inputs, and loading states. Remember the golden rule: never modify state directly. Always use the setter function React provides. This ensures your components re-render when data changes, keeping the interface synchronized with the underlying state.

Quiz

1. The DataFlow revenue tracker uses setRevenue to update the money amount. What does this setter function do?


2. Why does the broken user profile update fail when you mutate state directly?


3. Which line correctly creates a state variable for tracking DataFlow user count?


Up Next: Event Handling

Make your DataFlow components respond to clicks, form inputs, and keyboard actions with React's powerful event system.