ThisCalculator

Everyday

When to Use React API State

Updated · Standard formula, shown below

You should use React API state (via useState, useReducer, or a state management library) whenever the data you display or manipulate in your component comes from an external API and needs to be tracked over time. This includes the loading, success, and error phases of a request, plus any user edits to that fetched data. In short, if your UI depends on data that arrives asynchronously, that data belongs in state.

Background: Why React Needs State for API Data

React components are functions that render output based on their current props and state. Props are passed down from a parent and are immutable within the child. When you fetch data from an API, the data doesn’t exist at the moment the component first renders—it arrives later, after a network round-trip. Without state, there is no way to tell React that something changed and that it should re-render with the new data. State is React’s built-in mechanism for triggering re-renders when data changes over time.

Before hooks (React 16.8), class components used this.setState to achieve this. Today, the same logic lives in useState for simple values or useReducer for more complex state shapes. The core idea is unchanged: API data is inherently asynchronous and mutable, so it must live in state to be reflected in the UI.

How It Works: The Three Phases of an API Request

Every API call in a React component goes through at least three phases, and each phase needs its own piece of state:

  • Loading – a boolean flag that starts as true and becomes false when the request completes. This lets you show a spinner or skeleton.
  • Data – the actual response payload, initially null or an empty array, then populated with the server’s response.
  • Error – an error message or object, initially null, set when the request fails. This lets you show a friendly error and a retry button.

A typical pattern using useState and useEffect looks like this:

const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  fetch('/api/items')
    .then(res => res.json())
    .then(json => { setData(json); setLoading(false); })
    .catch(err => { setError(err.message); setLoading(false); });
}, []);

This is the minimal correct approach. The useEffect runs once after the first render, kicks off the fetch, and then the state updates trigger subsequent renders.

How to Choose Between useState, useReducer, and Libraries

You don’t always need a library. The choice depends on the complexity of your state and how many components share it.

  • useState – best for a single component that fetches one piece of data and doesn’t share it with siblings. Example: a dashboard widget that loads its own stats.
  • useReducer – best when the state has multiple sub-values that change together, or when you have many actions (e.g., fetching, refreshing, updating, deleting). The reducer centralizes the logic and makes transitions predictable.
  • Context + useReducer – when several components in a tree need the same API data. You put the state in a context provider and read it anywhere below.
  • Server-state libraries (TanStack Query, SWR) – when you have many API calls, caching, background refetching, or pagination. These libraries manage the loading/data/error states for you, plus caching and deduplication. They are not a replacement for local state; they are an addition.

A good rule of thumb: if you find yourself writing the same fetch logic in multiple components, or manually implementing cache invalidation, it’s time to use a dedicated server-state library. If you only have one or two calls, plain useState is simpler and perfectly fine.

Common Problems and Mistakes

Several pitfalls trip up developers new to API state:

  • Forgetting to handle the loading state – the component renders with null data and crashes when you try to access data.items. Always guard with a loading check or optional chaining.
  • Ignoring the error state – a failed fetch leaves the UI stuck on the loading spinner forever. Always set the error state in the catch block and display a message.
  • Setting state after unmount – if the component unmounts before the fetch resolves, calling setState triggers a warning. Use an AbortController or a cancelled flag to avoid it.
  • Over-fetching with useEffect dependencies – if you put an object or array in the dependency array, the effect runs on every render because the reference changes. Use specific primitives or an empty array when the call is one-time.
  • Storing derived data in state – if you can compute something from the fetched data (e.g., a filtered list), compute it during render instead of storing it. This avoids duplicate sources of truth.

Costs and Performance Considerations

Every state update triggers a re-render of the component and all its children. If you store a large API response in state and update it frequently, you may cause unnecessary renders. This is usually fine for typical data sizes, but for large lists or real-time data, consider:

  • Memoizing the list component with React.memo so it doesn’t re-render when the parent state changes.
  • Using a library that batches updates or provides selectors to avoid re-rendering the whole tree.
  • Debouncing or throttling if you are updating state on every keystroke (e.g., a search box that hits an API).

Also, be aware that storing data in state is not the same as storing it in a cache. If you navigate away and come back, the state is gone and you will fetch again. That’s acceptable for many apps, but if you want persistence across routes, you need a cache layer (like TanStack Query or a global store) or localStorage for offline access.

Alternatives to React State for API Data

Sometimes state is not the right place for API data. Consider these alternatives:

  • Server components (React Server Components) – in frameworks like Next.js, you can fetch data directly in a server component and pass it as props. This avoids client-side state entirely for initial render.
  • Global stores (Redux, Zustand, MobX) – when the data is needed in many unrelated components, a global store avoids prop drilling. But for pure server data, a server-state library is usually a better fit than a client store.
  • URL query parameters – for shareable or filterable data, put the filter values in the URL (via useSearchParams) instead of state. This makes the UI shareable and back-button friendly.
  • localStorage or IndexedDB – for data that should persist across sessions, like a draft or user preferences. This is not a replacement for state; it’s a persistence layer that you hydrate into state on load.

Frequently Asked Questions

Can I use a variable instead of state for API data?

No. A plain variable declared inside the component resets on every render. Even if you assign the fetched data to it, the component won’t re-render to show the new value. State is the only way to tell React that the data changed and the UI must update.

Should I store the whole API response in state or just the parts I need?

It’s usually fine to store the whole response, but if the response is huge and you only need a few fields, you can normalize it before storing. That means picking out the fields you need and discarding the rest. This reduces memory and makes your component simpler.

Do I need a state management library like Redux for API data?

Not necessarily. For a small app, useState or useReducer with Context is enough. For a large app with many API calls, a server-state library like TanStack Query or SWR handles caching and background updates better than Redux. Redux is for client state (UI flags, form inputs) more than server state.

What is the difference between state and props for API data?

Props are passed from a parent and are read-only. State is internal to a component and can be updated. If a parent fetches data and passes it down as props, the child doesn’t need state. But the parent must have the data in state to pass it down.

How do I avoid the “cannot update state on an unmounted component” warning?

Use an AbortController to cancel the fetch when the component unmounts, or set a let isMounted = true flag in the effect and set it to false in the cleanup. Then only call setState if isMounted is true.

Can I use a custom hook to manage API state?

Yes. A custom hook like useFetch(url) that returns { data, loading, error } is a great way to reuse the logic across components. It’s a common pattern and keeps your components clean.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.