← Back to Chapters

State vs Variables in React Native

⚛️ State vs Variables in React Native

? Quick Overview

In React Native, both state and variables are used to store data. However, they behave very differently when data changes and when the UI needs to update. Understanding this difference is critical for building dynamic mobile applications.

? Key Concepts

  • State is managed by React and triggers UI re-rendering.
  • Variables are plain JavaScript values.
  • State updates cause the component to refresh.
  • Variable updates do NOT refresh the UI.

? Syntax / Theory

In React Native functional components, state is created using the useState hook. Variables are declared using let, const, or var just like normal JavaScript.

? Code Example(s)

? View Code Example
// Import required hooks and components
import React, { useState } from "react";
import { View, Text, Button } from "react-native";

export default function App() {
  // Normal JavaScript variable
  let countVariable = 0;

  // React state variable
  const [countState, setCountState] = useState(0);

  return (
    <View>
      <Text>Variable Count: {countVariable}</Text>
      <Text>State Count: {countState}</Text>

      <Button
        title="Increase Variable"
        onPress={() => {
          countVariable = countVariable + 1;
        }}
      />

      <Button
        title="Increase State"
        onPress={() => {
          setCountState(countState + 1);
        }}
      />
    </View>
  );
}

? Live Output / Explanation

What happens?

  • Clicking Increase Variable does NOT update the UI.
  • Clicking Increase State updates the number instantly.
  • This proves that React only tracks changes in state.

? Interactive Explanation

Think of state as a remote control connected to the screen. Whenever state changes, React re-renders the screen. A normal variable is like writing on paper — React never notices the change.

? Component Simulator Try clicking buttons below
let variableCount = 0
const [state, setState] = 0
Waiting for input...

? Use Cases

  • Use state for counters, form inputs, toggles, API data.
  • Use variables for temporary calculations.
  • Never rely on variables to control UI updates.

✅ Tips & Best Practices

  • Always use state for UI-changing data.
  • Never mutate state directly.
  • Keep state minimal and meaningful.

? Try It Yourself

  1. Create a button that updates a variable.
  2. Create another button that updates state.
  3. Observe which one updates the UI.
  4. Convert the variable logic into state.