Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 71 ยท State and Data

State in React Native Apps

Choose where state lives in a React Native app: useState, useReducer, lifting state, context and stores, with mobile-specific traps and runnable stand-ins.

State is data that changes over time and makes the screen change with it: a text field's content, items in a cart, the signed-in user, whether a modal is open. React Native uses exactly the same state tools as web React: useState, useReducer, context and external stores. If you know them, you already know 90% of this lesson.

The remaining 10% is what makes mobile different. Screens in a stack stay mounted behind the new screen, the operating system can kill your app in the background and wipe all in-memory state, and one setState can re-render a long list that is already struggling to scroll smoothly. This lesson is a short recap with a mobile focus, plus a decision guide for where each piece of state should live. It follows the navigation chapter, starting with Stack Navigation with React Navigation.

What runs on this site. State logic is plain React, so the stand-ins here are real React 19 code; only the View, Text and Pressable pieces are replaced by HTML elements. The mobile-specific behavior (app kill, background, screens staying mounted) is described and shown as read-only code.

A quick recap

If any of these feel rusty, the web React lessons cover them in depth: useState, reducers, lifting state up, context and external stores.

JSX
import { useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';

function NameForm() {
  const [name, setName] = useState('');
  const [saved, setSaved] = useState(false);

  return (
    <View>
      <TextInput value={name} onChangeText={setName} placeholder="Your name" />
      <Pressable onPress={() => setSaved(true)} disabled={name.trim() === ''}>
        <Text>Save</Text>
      </Pressable>
      {saved && <Text>Saved {name}</Text>}
    </View>
  );
}

Three rules carry over unchanged: state is read-only until you call the setter, updates that depend on the previous value use the function form (setCount((c) => c + 1)), and objects and arrays are replaced, not mutated. Derived values (a total, a filtered list, a validity flag) should be computed during render, not stored in another state variable. Storing isValid next to name means you have two sources of truth that can disagree.

useReducer for screens with several moves

When one screen has several related pieces of state and several ways to change them, useReducer keeps the rules in one place. Instead of five setters scattered through event handlers, you describe what happened ({ type: 'added' }) and a pure function decides the next state.

JSX
function reducer(state, action) {
  switch (action.type) {
    case 'added':
      return { ...state, items: [...state.items, action.item] };
    case 'removed':
      return { ...state, items: state.items.filter((i) => i.id !== action.id) };
    case 'cleared':
      return { ...state, items: [] };
    default:
      return state;
  }
}

const [state, dispatch] = useReducer(reducer, { items: [] });

For mobile screens a reducer has a bonus: it is easy to test as a plain function, with no native modules involved, and it gives you one place to log every state change while debugging. The runnable example is a small water tracker.

A reducer-driven screen (stand-in)

total, percent and reached are never in state: they are recalculated from entries on every render, so they cannot go out of date.

Where should state live?

The most useful question to ask about any piece of state is "who needs it?". The answer picks the tool:

Who needs this state?

One component Keep it local with useState.
A few siblings Lift it to their parent.
A whole subtree Put it in context.
Many screens Use a store.

Start local and move up only when you must.

1 / 2
  • Local state (useState in the component that uses it) is the default. A form field, a toggle, an open dropdown.
  • Lifted state: two siblings need the same value, so it moves to their closest common parent and flows down as props, with callbacks flowing up. See lifting state up.
  • Context shares a value with a whole subtree without passing props through every level: current user, theme, language. Context is good for rarely changing values. Every consumer re-renders when the value changes, so putting a fast-changing object in one context can slow down big screens.
  • Stores (Zustand, Redux Toolkit and similar) hold state outside React and let components subscribe to slices, so only components that read the changed slice re-render. They are covered in Global State with Zustand and Redux Toolkit.
  • Server state (a list from an API) is not really "yours": it is a cache of someone else's data with loading, error and staleness. A query library handles it better than useState plus useEffect. See Server State with TanStack Query.
  • Navigation state (which screen is open, what params it has) belongs to the navigator. Do not mirror it in your own state; read it with useRoute and change it with navigation.

Context in practice

A context needs a provider near the top of the tree and a custom hook that reads it. Keep the hook next to the provider, and fail loudly when it is used outside:

JSX
const CartContext = createContext(null);

export function CartProvider({ children }) {
  const [items, setItems] = useState([]);
  const value = useMemo(
    () => ({
      items,
      add: (item) => setItems((list) => [...list, item]),
      count: items.length,
    }),
    [items]
  );
  return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}

export function useCart() {
  const ctx = useContext(CartContext);
  if (!ctx) throw new Error('useCart must be used inside CartProvider');
  return ctx;
}

useMemo keeps the value object stable between renders, so consumers do not re-render when only the provider's parent renders. In a navigation app, put providers above the NavigationContainer or navigators, so every screen, including screens in other tabs, sees the same values.

Two screens sharing context (stand-in)

Both screens and the tab bar read the same cart, although none of them passes props to the others. Try adding a lamp, then switching to the Cart tab.

Mobile-specific traps

1. State dies with the app. useState lives in memory. When the operating system kills a backgrounded app to free memory, or the user swipes it away, everything is gone. Anything that must survive (a draft, a token, a to-do list) needs to be saved: see Storing Data: AsyncStorage, MMKV and SecureStore.

2. Screens stay mounted. When you push a screen on a stack, the previous one is not unmounted: it keeps its state and its effects. That is great for preserving scroll position, but it means a setInterval in the screen underneath keeps ticking. Use useFocusEffect from React Navigation to start work on focus and clean up on blur:

JSX
import { useFocusEffect } from '@react-navigation/native';
import { useCallback } from 'react';

useFocusEffect(
  useCallback(() => {
    const id = setInterval(refresh, 30000);
    return () => clearInterval(id);
  }, [refresh])
);

3. Going back and forth creates new instances. push('Details') twice gives two screens with separate local state. If two screens must share the same data, it does not belong in either of them.

4. Large lists amplify re-renders. A setState in the screen that owns a FlatList re-renders the list's header, footer and any non-memoized row. Keep fast-changing state (a typed search query, a timer) in a small child component, or in a store with selectors. The lists chapter returns to this in FlatList Essentials.

5. Stale closures in callbacks. A function passed to a native event, a timer or a listener captures the state from the render that created it. Use the functional update form (setCount((c) => c + 1)) or refs for values that a long-lived callback must see fresh.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which value should NOT be kept in its own useState variable?

    Derived values are calculated during render. Storing them separately creates a second source of truth that can go out of sync.
  2. 2. Why does the screen below a pushed screen still run its setInterval?

    A stack keeps previous screens mounted. Use useFocusEffect to start and stop work as the screen gains and loses focus.
  3. 3. What is a good use of React context?

    Every consumer re-renders when the context value changes. Context suits stable, widely needed values; fast-changing or sliceable state fits a store better.
  4. 4. Your user typed a long draft and the OS killed the app in the background. What happens to the draft stored only in useState?

    useState is in-memory only. Persist anything that must survive an app restart.

Summary

  • React Native uses the same state tools as React: useState, useReducer, context and external stores.
  • Keep state as local as possible, lift it to a common parent when siblings share it, use context for rarely changing values and stores for shared, frequently updated data.
  • Compute derived values during render instead of storing them.
  • Server data, persisted data and navigation state each have a better home than plain useState.
  • On mobile, remember that state disappears when the app is killed, stacked screens stay mounted, and a re-render in a screen with a long list is expensive.
  • On this site the state stand-ins are real React code with HTML in place of native components.

Next, move shared state out of React in Global State with Zustand and Redux Toolkit.