Hasbi Hassadiqin
4 min readby Hasbi Hassadiqin

Understanding useState in React: The Subway Surfers Analogy

Ever wondered how games handle rapidly changing values like collecting coins? This is exactly how React's useState hook works - let me show you!

ReactuseStateHooksJavaScript

Loading...

Understanding useState in React: The Subway Surfers Analogy

Understanding useState in React

Have you ever wondered how games like Subway Surfers handle rapidly changing values, like collecting coins? This real-world example perfectly illustrates why React's useState hook is so powerful.

Content image

The Subway Surfers Problem

In Subway Surfers, players collect coins at an incredibly fast pace - sometimes 3, 4, or even 5 coins per second. If each coin collection needed to trigger a database save, the game would become unbearably slow due to constant server communication.

Instead, games like this use state management to handle these rapid updates smoothly, similar to how React's useState works.

Content image

What is useState?

Let's break down useState to understand its function:

javascript
import { useState } from "react";
const [state, setState] = useState(initialState); // Basic useState syntax
const [coins, setCoins] = useState(0); // Applied to our Subway Surfers example
Content image

Important Rules

  1. useState is a Hook - We can only use it at the top level of React components or custom hooks
  2. No loops or conditions - We can't place useState inside loops, conditions, or nested functions
  3. Must import - Always import it: import { useState } from 'react';

Why useState is Powerful

Instead of making database calls for every coin collection, React efficiently manages these updates in memory, only re-rendering the necessary parts of our interface when the state changes.

Content image
javascript
function CoinCounter() {
  const [coins, setCoins] = useState(0);
  const collectCoin = () => {
    setCoins(coins + 1); // Fast, in-memory update
    // No database call needed immediately!
  };
  return (
    <div>
      <h2>Coins: {coins}</h2>
      <button onClick={collectCoin}>Collect Coin!</button>
    </div>
  );
}

Real-World Applications

This pattern is fundamental to many interactive features we use daily:

Content image
  • Form input values - User typing in search boxes
  • Toggle switches - Dark/light mode toggles
  • Counter interfaces - Like buttons, shopping cart quantities
  • User preferences - Settings and configurations

The Bottom Line

Understanding useState is crucial for building responsive and efficient React applications. As my mentor emphatically puts it, "You need to learn useState a lottttttttttt, because we use it in every single development project!"

And yup, he is absolutely right.

Next time you're playing Subway Surfers and collecting coins rapidly, remember - that's exactly how useState manages your React app's data!

Share this article

More articles

Browse all articles