React
API
Select Options
Page Load
Frontend Development

How to populate select options from an Api call in React js on page load

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Populating a dropdown from an API is a standard React task, but the reliable version involves more than calling fetch once. You need to handle loading, request failures, and component unmounting so the select stays predictable when the page renders and when users navigate quickly.

Fetch Options on Initial Render

In a function component, the usual pattern is useEffect with an empty dependency array so the request starts once when the component mounts. Store the fetched list in state, and keep separate state for loading and error conditions.

jsx
1import { useEffect, useState } from "react";
2
3export default function CountrySelect() {
4  const [options, setOptions] = useState([]);
5  const [selected, setSelected] = useState("");
6  const [loading, setLoading] = useState(true);
7  const [error, setError] = useState("");
8
9  useEffect(() => {
10    let ignore = false;
11
12    async function loadCountries() {
13      try {
14        setLoading(true);
15        setError("");
16
17        const response = await fetch("/api/countries");
18        if (!response.ok) {
19          throw new Error(`Request failed with status ${response.status}`);
20        }
21
22        const data = await response.json();
23        if (!ignore) {
24          setOptions(data);
25        }
26      } catch (err) {
27        if (!ignore) {
28          setError(err.message);
29        }
30      } finally {
31        if (!ignore) {
32          setLoading(false);
33        }
34      }
35    }
36
37    loadCountries();
38    return () => {
39      ignore = true;
40    };
41  }, []);
42
43  return (
44    <div>
45      <label htmlFor="country">Country</label>
46      <select
47        id="country"
48        value={selected}
49        onChange={(e) => setSelected(e.target.value)}
50        disabled={loading || !!error}
51      >
52        <option value="">Select a country</option>
53        {options.map((country) => (
54          <option key={country.code} value={country.code}>
55            {country.name}
56          </option>
57        ))}
58      </select>
59
60      {loading && <p>Loading options...</p>}
61      {error && <p role="alert">{error}</p>}
62    </div>
63  );
64}

This assumes the API returns an array of objects with code and name fields. If your backend returns a different shape, normalize it before rendering instead of leaking backend details all over the component tree.

Normalize the API Response Early

A select component gets much easier to maintain when its options all use a consistent shape such as value and label. Converting the API response once lets the rendering logic stay simple.

jsx
1function toSelectOptions(rows) {
2  return rows.map((row) => ({
3    value: row.id,
4    label: row.displayName,
5  }));
6}

You can then store the normalized array in state and render from that. This is especially useful when one screen uses /api/users, another uses /api/projects, and both still want the same select component.

Abort Requests During Fast Navigation

The ignore flag shown earlier is enough to prevent state updates after unmount, but AbortController is even better because it cancels the network request itself. That matters when users switch routes quickly or type into a page that re-fetches based on filters.

jsx
1useEffect(() => {
2  const controller = new AbortController();
3
4  async function loadOptions() {
5    try {
6      const response = await fetch("/api/countries", {
7        signal: controller.signal,
8      });
9      const data = await response.json();
10      setOptions(data);
11    } catch (err) {
12      if (err.name !== "AbortError") {
13        setError(err.message);
14      }
15    } finally {
16      setLoading(false);
17    }
18  }
19
20  loadOptions();
21  return () => controller.abort();
22}, []);

For a one-time page-load request, this is usually the cleanest production pattern.

Keep the Select Controlled

A dropdown tied to API data should usually be a controlled input. That means the current value lives in React state and the value prop always reflects that state. Controlled components are easier to validate and easier to reset when upstream filters change.

For example, if the user changes a region and the list of countries is refreshed, you can clear the selected country deliberately:

jsx
setOptions(nextOptions);
setSelected("");

Without a controlled value, the browser may keep an option selected that no longer exists in the latest data set.

Handle Empty Results Explicitly

Do not treat an empty response as the same thing as a loading state. If the request succeeds but returns no options, tell the user that clearly.

jsx
{!loading && !error && options.length === 0 && (
  <p>No countries are available for this account.</p>
)}

This makes debugging easier too. A blank dropdown with no explanation leaves users guessing whether the page is broken, still loading, or simply has no data.

Common Pitfalls

A common mistake is trying to read the fetched array immediately after calling setOptions. State updates are asynchronous, so debug with the actual response data or with a separate useEffect that watches options.

Another problem is using array indexes as option keys. Use a stable identifier such as a code or database ID so React can reconcile option elements correctly.

Developers also often ignore failure states. If the API returns 401, 500, or invalid JSON, the select should not quietly stay empty without context.

Finally, avoid putting the fetched options array into the dependency list of the effect that loads those same options. That creates a request loop.

Summary

  • Fetch dropdown data in useEffect when the component mounts.
  • Keep separate state for options, loading, selected value, and errors.
  • Normalize API responses into a stable value and label shape.
  • Use a controlled select so resets and validation behave predictably.
  • Cancel or ignore stale requests when the component unmounts.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design