Mobile · PlenoMid-level

Estado e dados no mobile: do local ao gerenciamento global

Conforme um app cresce, a pergunta "onde guardo este dado?" aparece o tempo todo. A resposta depende de quanto tempo o dado precisa viver, quem mais o usa e qual o seu formato. Saber separar estado efêmero de tela do estado do app, e escolher entre key-value, banco local e store global, é o que distingue um pleno na hora de modelar dados.

Estado efêmero de tela vs estado do app

Nem todo dado tem a mesma importância. O estado efêmero pertence a uma tela e morre com ela: se um campo está expandido, qual aba está selecionada, o texto sendo digitado. Já o estado do app é compartilhado e duradouro: o usuário logado, o tema escolhido, o carrinho de compras.

A analogia: estado de tela é o rascunho num post-it que você joga fora; estado do app é o caderno que vários setores consultam. Tratar tudo como estado global infla o app desnecessariamente; tratar tudo como local força você a "passar o dado de mão em mão" entre telas.

Armazenamento local: key-value

Para pedaços pequenos e simples de configuração, todas as plataformas oferecem um armazenamento chave-valor: UserDefaults (iOS), SharedPreferences (Android), AsyncStorage (React Native). É como uma gavetinha de bilhetes: ótimo para "tema = escuro" ou "já viu o onboarding = sim", péssimo para listas grandes ou dados relacionados.

// key-value: pequeno e simples
prefs.set("tema", "escuro")
prefs.set("onboardingVisto", true)

let tema = prefs.get("tema")

Armazenamento local: banco

Quando os dados são muitos, estruturados e relacionados (uma lista de pedidos, mensagens, produtos em cache), você precisa de um banco local: SQLite na base, com camadas como Room (Android), Core Data (iOS) ou bibliotecas multiplataforma. Bancos permitem consultas, filtros e relações — coisa que a gaveta de bilhetes não faz.

Onde guardarUse paraNão use para
Memória (estado de tela)Dados temporários da UIAlgo que precisa sobreviver ao fechar
Key-valueFlags, preferências, tokens pequenosListas grandes, dados relacionais
Banco local (SQLite/Room/Core Data)Dados estruturados, cache de listasConfiguração trivial de 1 linha
Store global (estado do app)Sessão, tema, dados compartilhados em memóriaDado usado por uma única tela

Cache: nem fonte, nem lixo

Cache é uma cópia local de dados que vivem no servidor, mantida para ganhar velocidade e funcionar offline. A regra de ouro: cache pode ser descartado a qualquer momento sem perda real, pois a fonte da verdade está no backend. Confundir cache com armazenamento permanente leva a dados desatualizados ou perda do que deveria ser persistido. O cache é a base do offline-first.

Quando partir para estado global / store

Se você se pega passando o mesmo dado por cinco telas só para chegar na sexta ("prop drilling"), ou se vários pontos do app precisam reagir à mesma mudança (logout, troca de tema), é hora de um estado global: um store (Redux, Zustand, ViewModels compartilhados, Provider/Riverpod, ObservableObject). Ele centraliza o estado do app e notifica quem se interessa.

// store global: uma fonte, varios ouvintes
store.usuario = login(...)   // muda em um lugar
// telas inscritas re-renderizam sozinhas

É comum em entrevista pedir para você decidir "onde guardar X" em um cenário dado — e a resposta forte justifica a escolha pelo tempo de vida e pelo alcance do dado, não por hábito.

Não pergunte "qual ferramenta de estado usar", pergunte "quanto tempo este dado vive e quem precisa dele". A ferramenta cai naturalmente a partir daí.

Conclusão

Estado efêmero na memória da tela, configurações pequenas em key-value, dados estruturados em banco local, cache como cópia descartável e estado compartilhado num store global: cada dado tem seu lugar. Modelar isso com clareza deixa o app rápido, previsível e pronto para crescer — inclusive para funcionar sem rede.

As an app grows, the question "where do I store this data?" comes up all the time. The answer depends on how long the data needs to live, who else uses it and what shape it has. Knowing how to separate ephemeral screen state from app state, and how to choose between key-value, a local database and a global store, is what sets a mid-level apart when modeling data.

Ephemeral screen state vs app state

Not all data is equally important. Ephemeral state belongs to a screen and dies with it: whether a field is expanded, which tab is selected, the text being typed. App state, on the other hand, is shared and long-lived: the logged-in user, the chosen theme, the shopping cart.

The analogy: screen state is the scribble on a sticky note you throw away; app state is the notebook several departments consult. Treating everything as global state needlessly bloats the app; treating everything as local forces you to "hand the data from screen to screen".

Local storage: key-value

For small, simple pieces of configuration, every platform offers a key-value store: UserDefaults (iOS), SharedPreferences (Android), AsyncStorage (React Native). It's like a little drawer of notes: great for "theme = dark" or "has seen onboarding = yes", terrible for large lists or related data.

// key-value: small and simple
prefs.set("theme", "dark")
prefs.set("onboardingSeen", true)

let theme = prefs.get("theme")

Local storage: database

When data is large, structured and related (a list of orders, messages, cached products), you need a local database: SQLite at the base, with layers such as Room (Android), Core Data (iOS) or cross-platform libraries. Databases allow queries, filters and relationships — things the drawer of notes can't do.

Where to storeUse forDon't use for
Memory (screen state)Temporary UI dataAnything that must survive closing
Key-valueFlags, preferences, small tokensLarge lists, relational data
Local database (SQLite/Room/Core Data)Structured data, list cachesTrivial one-line configuration
Global store (app state)Session, theme, data shared in memoryData used by a single screen

Cache: neither source nor trash

A cache is a local copy of data that lives on the server, kept for speed and to work offline. The golden rule: a cache can be discarded at any time with no real loss, because the source of truth is in the backend. Confusing cache with permanent storage leads to stale data or loss of what should have been persisted. Cache is the foundation of offline-first.

When to move to global state / a store

If you find yourself passing the same data through five screens just to reach the sixth ("prop drilling"), or if several parts of the app need to react to the same change (logout, theme switch), it's time for global state: a store (Redux, Zustand, shared ViewModels, Provider/Riverpod, ObservableObject). It centralizes app state and notifies whoever is interested.

// global store: one source, many listeners
store.user = login(...)   // changes in one place
// subscribed screens re-render on their own

Interviewers often ask you to decide "where to store X" in a given scenario — and a strong answer justifies the choice by the data's lifetime and reach, not by habit.

Don't ask "which state tool should I use"; ask "how long does this data live and who needs it". The tool follows naturally from there.

Conclusion

Ephemeral state in the screen's memory, small settings in key-value, structured data in a local database, cache as a disposable copy and shared state in a global store: every piece of data has its place. Modeling this clearly keeps the app fast, predictable and ready to grow — including working without a network.

Leia também

Voltar à trilhaBack to the track