React: Cannot read properties of undefined (reading 'map')
The map error means a value you expected to be an array is undefined. Initialise state, validate the API shape and keep an honest loading branch.

Introduction & Quick Summary
The browser console says only this, with a minified stack you cannot read:
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
at BlogList (chunk-4f9a1c.js:1:8421)Quick answer: something you expected to be an array is undefined. Give it a default and stop trusting the shape:
export function BlogList({ posts }: { posts?: Post[] }) {
if (!posts?.length) return <p>No posts yet.</p>;
return (
<ul>
{posts.map((p) => (
<li key={p.slug}>{p.title}</li>
))}
</ul>
);
}The message is React's, but the bug is ordinary JavaScript: x.map is evaluated before the call, and x is undefined. In React the usual suspects are narrow and repeatable — state initialised as null, a prop that was never passed, an API response whose shape is not what the component assumes, and a useEffect that renders once before the fetch resolves. Each has a different right fix, so identify which one you have before adding ?. everywhere.
Core Mechanics, Signatures & Reproducible Setup
Array.prototype.map exists only on arrays. The error text names the reason undefined appeared, not the property you called, which is why "reading 'map'" is a symptom rather than a diagnosis. Reproduce it in one file:
import { useEffect, useState } from "react";
type Post = { slug: string; title: string };
export function Broken() {
const [posts, setPosts] = useState<Post[]>(); // undefined, not []
useEffect(() => {
fetch("/api/posts")
.then((r) => r.json())
.then((d) => setPosts(d.items)); // shape assumed
}, []);
return <ul>{posts.map((p) => <li key={p.slug}>{p.title}</li>)}</ul>;
}Two defects are stacked here. useState<Post[]>() declares the state type but the value starts as undefined, so the first render throws before the effect runs. And d.items is an assumption; when the API returns { data: { items } } the second render throws instead.
Calling .map on something that is not an array produces related messages:
| Value | Message you see | Real shape |
|---|---|---|
undefined | Cannot read properties of undefined (reading 'map') | missing or not yet loaded |
null | Cannot read properties of null (reading 'map') | explicitly empty state |
{} | x.map is not a function | object where array expected |
"abc" | x.map is not a function | string |
NodeList | x.map is not a function | Array.from(x) first |
Key Comparison Table
Where the undefined comes from, and the fix that belongs to each cause:
| Cause | Typical code | Correct fix |
|---|---|---|
| State has no initial value | useState<Post[]>() | useState<Post[]>([]) |
| Prop never passed | <List /> with optional prop | required prop or default parameter |
| API shape mismatch | setPosts(res.data) when it is an envelope | read the real field, type it |
| Effect has not run yet | first render before fetch | loading state, not a guard |
| Context default | createContext(null) | default to an empty array |
| Conditional reset | setPosts(data.error ? undefined : data) | keep the type honest |
Guard styles, ranked by how much they hide:
| Style | Keeps the error visible | Handles nested data | Good for |
|---|---|---|---|
useState<Post[]>([]) | yes | no | state with an array type |
Array.isArray(x) | yes | no | data from JSON.parse |
x?.map(...) | no, renders nothing | yes | genuinely optional lists |
(x ?? []).map(...) | no | yes | one-off local guards |
| Validate at the boundary | yes, with a clear error | yes | APIs, fetch, storage |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Initialise state to the type you declared
useState<Post[]>() is legal TypeScript that produces undefined. The generic says what the value will be later, not what it is now.
const [posts, setPosts] = useState<Post[]>([]);
const [selected, setSelected] = useState<Post | null>(null);The same trap appears with useRef<Post[]>(), whose .current starts as undefined, and with let items: Post[]; inside a component body. Whenever a value is read during render, it needs a value during render.
2. Props without defaults fail only where they are used
type Props = { posts?: Post[] };
export function List({ posts = [] }: Props) {
return <ul>{posts.map((p) => <li key={p.slug}>{p.title}</li>)}</ul>;
}A default parameter is cheaper than a guard at every call site, and it documents the intent: "this component works with no rows". If a list is required, keep the prop required and let the parent fail at compile time instead. The middle ground — optional prop, no default, posts.map in the body — is the one that reaches production.
3. API envelopes are the most common real cause
type Envelope<T> = { data: T; meta: { page: number } };
async function loadPosts(): Promise<Post[]> {
const res = await fetch("/api/posts");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body: unknown = await res.json();
const env = body as Envelope<{ posts: Post[] }>;
return Array.isArray(env?.data?.posts) ? env.data.posts : [];
}Axios adds a layer: const res = await axios.get(...) puts the payload in res.data, so res.data.posts is correct and res.items is undefined. Supabase returns { data, error }, and data is null on error, not []. Print the real body once with the JSON formatter instead of guessing, and turn an exported CSV or a pasted payload into JSON with the CSV to JSON converter when the data comes from a spreadsheet.
4. Nested access and the loading state
posts.map is one level deep; post.comments.map inside the row can throw on the second item after the list rendered fine.
{posts.map((p) => (
<article key={p.slug}>
<h2>{p.title}</h2>
{(p.comments ?? []).map((c) => (
<p key={c.id}>{c.body}</p>
))}
</article>
))}For the list itself, prefer an explicit loading branch over an empty-array default when the difference matters to the user:
if (status === "loading") return <Skeleton rows={3} />;
if (status === "error") return <Retry onRetry={reload} />;
if (posts.length === 0) return <EmptyState />;That reads better than a list that flickers "No posts yet" for 300 ms on every navigation.
5. Production stacks, error boundaries and query libraries
In a minified build the stack points into a chunk. Upload source maps and the same error names the component and line. Until then, an error boundary converts the white screen into a message you can act on:
class Boundary extends React.Component<{ children: React.ReactNode }, { error?: Error }> {
state: { error?: Error } = {};
static getDerivedStateFromError(error: Error) { return { error }; }
render() {
if (this.state.error) return <pre>{this.state.error.message}</pre>;
return this.props.children;
}
}With TanStack Query the equivalent fix is const { data = [] } = useQuery(...), or destructuring data only when isSuccess is true. Note that query.data is undefined until the first success — the library is telling you the truth, and a data = [] default is the intended contract.
6. .map on the wrong thing entirely
Three variants look like the same bug and are not:
Object.values(record).map(...)whenrecordis an array already — harmless, but the types are wrong somewhere.document.querySelectorAll(...).map(...)— aNodeListhasforEachbut nomap; useArray.from.new Map()shadowingArray.prototype.map: a local variable namedmapor a state setter namedmapproduces "is not a function" at the call site.
Common Compilation/Runtime Mistakes & Version Gotchas
Silencing with as. (posts as Post[]).map(...) compiles and crashes exactly as before. A type assertion removes the warning, not the undefined.
Defaulting to [] so the error disappears. This is correct for state, but it hides a broken API contract. Validate once at the boundary and keep the rest of the app honest.
Optional chaining on the result. posts?.map(...) renders nothing at all, with no message, during the exact render where the user needed feedback. Pair it with a fallback.
Ignoring cleanup and races. Two overlapping requests can resolve out of order, so the second render may set undefined from a stale response. Use an AbortController or an ignore flag:
useEffect(() => {
let cancelled = false;
load().then((rows) => { if (!cancelled) setPosts(rows); });
return () => { cancelled = true; };
}, []);Version notes. React 18 added Strict Mode double-invocation in development, which surfaces effect bugs that used to stay hidden. React 19 changed error reporting for uncaught render errors and added use() for promises, which removes the "render before data" window in components that use it. React 19 also stopped swallowing some errors that previously logged silently, so .map crashes in event handlers now reach the console more reliably than they used to.
Reference material: Rendering lists and Conditional rendering.
Official references
primary documentationThe React documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact 19: Support for defaultProps will be removed
React 19 ignores defaultProps on function components, so a default becomes undefined. Move defaults into the parameter list and handle null honestly.
React: Each child in a list should have a unique key prop
Keys tell React which item is which between renders. Use stable ids, avoid index keys and put the key on the mapped element, not on a wrapper.
react-hook-form with zod 4: resolver type errors after the upgrade
Zod 4 split input from output and resolvers v5 re-typed Resolver. Drop the generic, or pass all three, and the errors disappear.
React Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
More in React
All React guidesThe guides filed next to this one in React, in library order.