Choose between local, URL, server and global state
Choose an owner before a library
State architecture starts with who owns a value, how long it lives, and who needs to observe it. A search query that should survive sharing belongs in the URL. A temporary open panel belongs near the component. A server-owned catalogue needs a fetch/cache layer that tracks freshness and mutations. A cross-workspace preference may belong in a scoped store. Avoid duplicating one canonical value across all four systems.
import React, {useState, useEffect, createContext, useContext} from 'react';import {create, useStore} from 'zustand';import {createStore} from 'zustand/vanilla';import {useShallow} from 'zustand/react/shallow';import {persist, createJSONStorage, subscribeWithSelector, devtools} from 'zustand/middleware';import {MemoryRouter,useSearchParams} from 'react-router';const books=[{id:'a',title:'Botany'},{id:'b',title:'Geology'},{id:'c',title:'Botany notes'}];function filterTitles(rows,query){return rows.filter(row=>row.title.toLowerCase().includes(query.trim().toLowerCase()));}function Panel(){const [params,setParams]=useSearchParams();const [help,setHelp]=useState(false);const query=params.get('q')??'';const rows=filterTitles(books,query);return <section><label>Filter <input value={query} onChange={e=>setParams(old=>{const next=new URLSearchParams(old);if(e.target.value)next.set('q',e.target.value);else next.delete('q');return next;},{replace:true})}/></label><button aria-expanded={help} onClick={()=>setHelp(v=>!v)}>Help</button>{help&&<p>Search by title.</p>}<ul>{rows.map(row=><li key={row.id}>{row.title}</li>)}</ul>{rows.length===0&&<p>No results</p>}</section>;}export default function App(){return <MemoryRouter initialEntries={['/?q=botany']}><Panel/></MemoryRouter>;}The initial route shows Botany and Botany notes. Changing the query to geology shows only Geology. Help visibility remains local and does not change the query. MemoryRouter simulates a URL in memory; use a browser router when a real address must be shareable and the hosting setup supports it. URL values are untrusted public input; never put secrets in search parameters. This example uses static catalogue data to isolate ownership, not to simulate a real server cache.
Separate fetched data from display preferences
import React, {useState, useEffect, createContext, useContext} from 'react';import {create, useStore} from 'zustand';import {createStore} from 'zustand/vanilla';import {useShallow} from 'zustand/react/shallow';import {persist, createJSONStorage, subscribeWithSelector, devtools} from 'zustand/middleware';import {QueryClient,QueryClientProvider,useQuery} from '@tanstack/react-query';function makeStore(){return createStore(set=>({dense:false,toggle:()=>set(s=>({dense:!s.dense}))}));}async function readCatalogue(){return [{id:'a',title:'Botany'},{id:'b',title:'Geology'}];}function Panel({store}){const dense=useStore(store,s=>s.dense);const query=useQuery({queryKey:['catalogue'],queryFn:readCatalogue,staleTime:60000,retry:false});return <section><button onClick={()=>store.getState().toggle()}>Toggle layout</button>{query.isPending?<p role="status">Loading</p>:query.isError?<p role="alert">Could not load</p>:<ul style={{lineHeight:dense?1.2:1.8}}>{query.data.map(row=><li key={row.id}>{row.title}</li>)}</ul>}</section>;}export default function App(){const [client]=useState(()=>new QueryClient());const [store]=useState(makeStore);return <QueryClientProvider client={client}><Panel store={store}/></QueryClientProvider>;}The query resolves two synthetic records and the layout button only changes spacing. TanStack Query v5 owns request results and freshness. Zustand owns density, not a copied catalogue. In an actual app, include all request parameters and relevant account scope in query keys. Use server authorization independently of frontend caches. Do not persist private query results without a reviewed policy. The local async function does not test HTTP or network error handling.
Compare trade-offs with an explicit isolation check
import React, {useState, useEffect, createContext, useContext} from 'react';import {create, useStore} from 'zustand';import {createStore} from 'zustand/vanilla';import {useShallow} from 'zustand/react/shallow';import {persist, createJSONStorage, subscribeWithSelector, devtools} from 'zustand/middleware';function createPreferences(initial='comfortable') { return createStore((set,get)=>({density:initial, count:0, toggle:()=>set(s=>({density:s.density==='compact'?'comfortable':'compact'})), increment:()=>set(s=>({count:s.count+1})), reset:()=>set({density:initial,count:0}), isCompact:()=>get().density==='compact'}));}const StoreContext=createContext(null);function Scope({children,initial}){ const [store]=useState(()=>createPreferences(initial)); return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;}function usePrefs(selector){const store=useContext(StoreContext);if(!store)throw new Error('Missing Scope');return useStore(store,selector);}export default function App(){const [result,setResult]=useState('Not run');function run(){const a=createPreferences('comfortable');const b=createPreferences('compact');a.getState().increment();a.getState().toggle();const isolated=b.getState().count===0&&b.getState().isCompact();a.getState().reset();setResult(isolated&&a.getState().count===0&&!a.getState().isCompact()?'PASS':'FAIL');}return <section><button onClick={run}>Check independent stores</button><p role="status">{result}</p></section>;}The expected result is PASS, not an observed result until run with Zustand. A local useState fits small independent controls. A reducer plus context fits a feature with explicit transitions and limited sharing. Redux Toolkit adds conventions for action tracing, middleware and normalized complex client data. Zustand offers direct store actions and granular subscriptions with fewer required conventions, but teams must define ownership and lifecycle themselves. URL state fits navigable filters and page identifiers. TanStack Query or RTK Query fits remote records and request lifecycles; do not keep both caches for the same resource without a clear boundary. Measure rendering costs rather than selecting a library based on popularity. Tests should create new stores and caches per case, reset known state, unmount subscriptions and verify actual rendered behavior. In SSR, do not share user-specific stores or caches between requests.
Practice
Assign an owner to a modal, catalogue search, remote book inventory, shared reading density and a multi-step checkout draft. Explain when the checkout should move from local reducer to a scoped external store. Write a test that updates one workspace and checks the other is unchanged.