Error: Minified React error 31; visit https://reactjs.org/docs/error-decoder.html?invariant=31 for the full message or use the non-minified dev environment for full errors and additional helpful warnings. - 12 Causes and Fixes

Your production bundle crashed with Error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31 for the full message or use the non-minified dev environment for full errors and additional helpful warnings. and the stack trace is a wall of one-letter function names. Decoded, invariant 31 says: Objects are not valid as a React child — you put a plain JavaScript object where React expected text or an element.

React never prints [object Object] the way a string template would. It refuses, because guessing how to stringify your object would hide a bug instead of surfacing it.

This page gives you the one-line fix, then 12 distinct causes with a reproduction and a corrected snippet each, a checklist for when your case matches none of them, and the reason React made this a hard error instead of a warning. Close-up of a laptop screen displaying code, set against a dark backdrop with blue lighting for a tech-focused ambiance.

ErrorError: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
Where it happensReact (production/minified build) - browser, React Native, or SSR via Next.js/Remix; thrown during render, not at build time. The development build prints the same failure as: "Objects are not valid as a React child (found: object with keys {...})".
What it meansSomething inside your JSX children is a plain object (or a class instance), and React only knows how to render strings, numbers, elements, arrays, null, undefined, and booleans.

The Fast Fix

Find the JSX expression that renders an object and render one field of it instead, as a string or number.

// before - user is { id: 7, name: "Ada" }
<p>{user}</p>

// after
<p>{user.name}</p>

// temporary, while you find out what the object actually is
<pre>{JSON.stringify(user, null, 2)}</pre>

To see which object and which component, run the same code against a development build of React: the full message lists the object's keys and a component stack. The keys usually identify the culprit instantly — {current} is a ref, {message, stack} is an Error, {_id} is a Mongo document, {amount, currency} is a money object.

What Is Actually Causing It

1. You render the whole object instead of one of its fields

Reproduce it

function Profile({ user }) {
  // user = { id: 7, name: "Ada", email: "ada@example.com" }
  return <h1>Welcome, {user}</h1>;
}

Why it happens — React walks the children of <h1> and finds a plain object. Objects have no defined text representation in React's reconciler, so it throws invariant 31 instead of silently printing [object Object].

The fix

function Profile({ user }) {
  return <h1>Welcome, {user.name}</h1>;
}

Changed: the expression now resolves to a string, not the containing object.

Confirm it worked — Add console.log(typeof user, user) just above the return. A fixed component logs the field as string or number; object means you are still one property short.


2. Double curly braces created an object literal in JSX

Reproduce it

function Card({ title }) {
  return <h2>{{ title }}</h2>; // two braces = { title: title }
}

Why it happens — The outer braces open a JSX expression; the inner braces build an object literal. {{ title }} is shorthand for { title: title }, so you are passing an object with one key as the child. This is the standard mistake when coming from Vue or Angular template syntax.

The fix

function Card({ title }) {
  return <h2>{title}</h2>; // single pair of braces
}

Changed: one pair of braces. The only legitimate use of {{ }} in JSX is an inline object prop such as style={{ color: 'red' }}.

Confirm it worked — Search the file for {{ and confirm every hit sits in a prop position (style={{, sx={{), never between an opening and closing tag.


3. A .map() callback returns the array items, not elements

Reproduce it

function UserList({ users }) {
  // users = [{ id: 1, name: "Ada" }, { id: 2, name: "Linus" }]
  return <ul>{users.map((user) => user)}</ul>;
}

Why it happens — Arrays are valid children — React flattens them and renders each entry. That is why the array itself passes and the objects inside it fail. The error surfaces on the first element, so it looks like a list bug rather than a mapping bug.

The fix

function UserList({ users }) {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Changed: the callback returns an element whose text child is a string field.

Confirm it worked — Log the mapped output: console.log(users.map((u) => u.name)) should print an array of strings. Any {} in that output is still a bad child.


4. A Date or other built-in instance is rendered directly

Reproduce it

function Post({ post }) {
  // post.publishedAt is a Date instance, e.g. from new Date(iso)
  return <time>{post.publishedAt}</time>;
}

Why it happens — Date, Map, Set, URL, and RegExp instances are objects, not primitives. A JSON API gives you a string here, so the bug appears only after someone adds a new Date(...) conversion or a date-parsing library in the data layer.

The fix

function Post({ post }) {
  const date = new Date(post.publishedAt); // safe whether it is a string or a Date
  return (
    <time dateTime={date.toISOString()}>{date.toLocaleDateString('en-US')}</time>
  );
}

Changed: the child is the result of toLocaleDateString(), a string. Map and Set need [...value].join(', ') or an explicit render, not a cast.

Confirm it worked — console.log(post.publishedAt instanceof Date) — if it logs true, that value must be formatted before it reaches JSX.


5. An async function call inside JSX returns a Promise

Reproduce it

async function fetchName(id) {
  const res = await fetch(`/api/users/${id}`);
  return (await res.json()).name;
}

export default function Profile({ id }) {
  return <h1>{fetchName(id)}</h1>; // a Promise, not a string
}

Why it happens — Calling an async function returns a Promise object immediately. In a classic client component this is error #31; it also re-fires the request on every render. (Some newer React setups can render a promise under Suspense — do not rely on that in a plain client component.)

The fix

export default function Profile({ id }) {
  const [name, setName] = useState('');

  useEffect(() => {
    let active = true;
    fetchName(id).then((value) => {
      if (active) setName(value);
    });
    return () => {
      active = false;
    };
  }, [id]);

  return <h1>{name}</h1>;
}

Changed: the awaited value lands in state, and JSX renders the string. A data library such as React Query gives you the same shape with caching.

Confirm it worked — Log the suspect expression: console.log(fetchName(id) instanceof Promise). true means the value can never be a valid child.


6. A caught error value is rendered as-is

Reproduce it

function Form() {
  const [error, setError] = useState(null);

  async function submit() {
    try {
      await save();
    } catch (err) {
      setError(err); // an Error instance, or a thrown object literal
    }
  }

  return <>{error && <p className="error">{error}</p>}</>;
}

Why it happens — Error instances are objects, and message is not an own enumerable property, so even a JSON.stringify of them looks empty. Worse, anything can be thrown — a rejected fetch wrapper often throws { status, body }, which is also an object.

The fix

function toMessage(err) {
  if (err instanceof Error) return err.message;
  if (typeof err === 'string') return err;
  return 'Something went wrong.';
}

// ...
{error && <p className="error">{toMessage(error)}</p>}

Changed: the thrown value is narrowed to a string before it reaches JSX. Use the same helper in your error boundary's fallback.

Confirm it worked — Force the failure path (throw in save()), and confirm the UI shows readable text while console.error(err) still shows the full object.


More causes (6 remaining)

7. A hook's result object was never destructured

Reproduce it

function User() {
  const data = useQuery({ queryKey: ['user'], queryFn: getUser });
  return <h1>{data}</h1>;
}

Why it happens — useQuery returns a result object ({ data, isLoading, error, ... }), not the payload. Naming that object data makes the mistake invisible on the next line. The same trap applies to any hook that returns an object or tuple.

The fix

function User() {
  const { data, isLoading } = useQuery({ queryKey: ['user'], queryFn: getUser });
  if (isLoading) return <p>Loading…</p>;
  return <h1>{data?.name}</h1>;
}

Changed: destructured the result, then rendered a leaf field, plus a loading branch so the first render has nothing object-shaped to print.

Confirm it worked — console.log(Object.keys(data)) — seeing isLoading, error, or status in that list means you are logging the wrapper, not the payload.


8. The API changed shape: a string field is now an object

Reproduce it

// response used to be { price: 19.99 }
// response is now  { price: { amount: 1999, currency: "USD" } }
function PriceTag({ product }) {
  return <span>{product.price}</span>;
}

Why it happens — Nothing in the frontend changed; the contract did. If the response was typed as any (or the types are hand-written and stale), TypeScript will not catch it either, so the first signal is error #31 in production for the records that use the new shape.

The fix

import { z } from 'zod';

const Product = z.object({
  price: z.object({ amount: z.number(), currency: z.string() }),
});

function PriceTag({ product }) {
  const { amount, currency } = Product.parse(product).price;
  return <span>{(amount / 100).toFixed(2)} {currency}</span>;
}

Changed: the payload is validated at the boundary, and JSX renders primitives. The parse failure now points at the field instead of at the renderer.

Confirm it worked — Call the endpoint directly (curl, or the Network tab) and compare the JSON against your type for that field. Drift in either direction is the bug.


9. An ORM or driver wrapper value reaches the view

Reproduce it

// order.total is a Prisma Decimal; user._id is a BSON ObjectId
function OrderRow({ order, user }) {
  return (
    <tr>
      <td>{user._id}</td>
      <td>{order.total}</td>
    </tr>
  );
}

Why it happens — Decimal, BigNumber, and ObjectId are class instances that only look like scalars in a console log, because their toString() is friendly. React does not call toString() on children, so they arrive as objects.

The fix

function OrderRow({ order, user }) {
  return (
    <tr>
      <td>{String(user._id)}</td>
      <td>{order.total.toString()}</td>
    </tr>
  );
}

Changed: explicit string conversion. The durable fix is to serialize these to primitives in the server/loader layer so the view only ever receives JSON-safe values.

Confirm it worked — console.log(Object.prototype.toString.call(order.total), order.total.constructor?.name) — anything other than a primitive means it must be converted before render.


10. A translation key or rich-text field resolves to an object

Reproduce it

// en.json: { "home": { "title": "Welcome" } }
function Home() {
  const { t } = useTranslation();
  return <h1>{t('home')}</h1>; // returns the namespace object
}

Why it happens — Pointing a lookup at a parent node returns the subtree, not a leaf string. The same thing happens with CMS rich text: a Contentful or Portable Text field is a document tree, and it needs a renderer, not interpolation.

The fix

function Home() {
  const { t } = useTranslation();
  return <h1>{t('home.title')}</h1>; // leaf key
}

Changed: the key points at a leaf. For rich text, pass the document to the library's renderer component instead of rendering it as a child.

Confirm it worked — console.log(typeof t('home.title')) must print string. For a missing key, the lookup returns the key itself — also a string, so the page renders and you see the raw key instead of a crash.


11. Intl.NumberFormat or DateTimeFormat used without calling format()

Reproduce it

const currency = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

function Total({ price }) {
  return <span>{currency}</span>;
}

Why it happens — The constructor returns a formatter object; the string only exists after you call format(value) on it. Easy to hit when you extract the formatter to module scope and then forget the call site.

The fix

function Total({ price }) {
  return <span>{currency.format(price)}</span>;
}

Changed: added the .format(price) call so the child is a string.

Confirm it worked — console.log(currency.format(1).length > 0) prints true, and console.log(typeof currency) prints object — confirming the formatter must be invoked.


12. A ref or context container object is rendered instead of its value

Reproduce it

function Search() {
  const inputRef = useRef('');
  return (
    <>
      <input ref={inputRef} />
      <p>You typed: {inputRef}</p> {/* { current: ... } */}
    </>
  );
}

Why it happens — useRef returns { current }, and a context object from createContext has Provider/Consumer keys. Both are containers. Refs also do not trigger re-renders, so reading inputRef.current during render would be unreliable even if it were a string.

The fix

function Search() {
  const [query, setQuery] = useState('');
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <p>You typed: {query}</p>
    </>
  );
}

Changed: rendered value moved into state. For context, render useContext(MyContext).someField — never the context object itself.

Confirm it worked — In the development build, the full message lists the keys. object with keys {current} is a ref; {Provider, Consumer} is a context object.

Close-up of HTML and JavaScript code on a computer screen in Visual Studio Code. ## None of Those? Narrow It Down
  1. Decode the number first: open https://reactjs.org/docs/error-decoder.html?invariant=31 (newer React versions link to react.dev/errors/31). #31 always means "Objects are not valid as a React child" — if the decoder shows a different sentence, you are reading a different code and the rest of this page does not apply.
  2. Reproduce against a development build of React (NODE_ENV=development, or your framework's dev server) with the same data. The dev message lists the object's keys and a component stack, which names the file. If it does not reproduce in dev, the trigger is data-dependent, not code-dependent — go to step 5.
  3. Read the keys in the full message and match them to a known shape: {current} is a ref, {message, stack} is an Error, {Provider, Consumer} is a context, {_id} or {amount, currency} is a server payload, {data, isLoading} is a hook result. This usually identifies the cause above without any further searching.
  4. If you only have the minified stack, deploy or serve the build with source maps and re-read the trace, or bisect: comment out half of the suspect component's JSX and reload. The half that stops crashing contains the bad child.
  5. Inspect the actual response for the failing view in the Network tab and compare it field by field against the type or interface you render. A field that is an object where your code expects a string is contract drift (cause 8), not a render bug.
  6. Check whether it fails for every record or only some: query or filter your data for rows where the suspect field is not a string. Failing on a subset points at nullable or polymorphic fields; failing on all of them points at a code-level mistake.
  7. Still unidentified: wrap the suspect expression in a temporary guard — {(() => { if (value && typeof value === 'object') { console.error('bad child', value); return null; } return value; })()} — then reload and read the console. It converts the crash into a labelled log with the real object.

Why This Error Exists At All

React's reconciler accepts a closed set of child types: strings and numbers (rendered as text), React elements (rendered as components or DOM nodes), arrays and iterables (flattened and rendered item by item), and null, undefined, false, true (rendered as nothing). That list is the whole contract. Anything else has no defined rendering, and rather than inventing one, React throws.

The alternative would be to call String(child), which is what string templates and most server-side template languages do. That gives you [object Object] in the DOM — a bug that ships, passes review, and gets reported by a user three weeks later. React made the deliberate choice to fail loudly at the boundary where an unrenderable value enters the tree, because a stack trace at render time is cheaper than a visual bug in production. The same philosophy produces its sibling errors: an invalid element type (#130) rather than an empty node, and a key warning rather than silently reusing DOM.

The second half of the message is a separate design decision about bundle size. React's invariant calls are rewritten at build time: the human-readable sentence is stripped from production builds and replaced with a numeric code, because shipping hundreds of error strings costs real kilobytes to every visitor. The decoder URL is how you get the sentence back. So the message you are reading is actually two facts stacked together — an object reached the children position, and you are on a production build, so go look up the text. Once you internalise that, every Minified React error #N becomes a two-step process instead of a mystery: decode the number, then reproduce on a dev build to get the component stack. Software developer analyzing code on a tablet in a modern office workspace.

Stop It From Coming Back

  • Type children explicitly with TypeScript: children: React.ReactNode and props as concrete field types rather than any. ReactNode excludes plain objects, so <p>{user}</p> fails at compile time instead of at render time.
  • Validate API responses at the network boundary with zod (or io-ts / valibot) and render only the parsed result. Contract drift then throws a message naming the field, not a minified React code.
  • Serialize non-primitive values in the server/loader layer: convert Prisma Decimal, BSON ObjectId, and Date to strings or numbers before the payload reaches a component, so no wrapper object can reach JSX.
  • Enable @typescript-eslint/no-base-to-string to catch values whose only string form is [object Object], and keep eslint-plugin-react on so JSX mistakes are flagged in the editor.
  • Write a React Testing Library test per data-driven component that renders an object-shaped fixture for every nullable or polymorphic field. The error is deterministic, so a single render assertion catches it in CI.
  • Ship source maps for your production bundle and wrap routes in an error boundary that logs error.message plus the component stack to your monitoring tool. You then get the decoded message and the component name from the first real-world occurrence.

Related Guides

Errors You Will Probably Hit Next

  • Minified React error #130: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
  • Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render.
  • TypeError: Cannot read properties of undefined (reading 'map')

Treat Minified React error #31 as two instructions in one: decode the number, then reproduce on a development build to get the object's keys and the component stack. Those keys name the culprit faster than any search — {current} is a ref, {message, stack} is an Error, {amount, currency} is a payload you forgot to unwrap. The fix is always the same move: resolve the expression down to a string, a number, or an element before it reaches the children position, and validate the data shape where it enters your app rather than where it renders.

댓글

이 블로그의 인기 게시물

TypeError: Cannot read properties of undefined (reading 'map') - 11 Causes and Fixes

psql: FATAL: password authentication failed for user - 10 Causes and Fixes

Error: ERR_MODULE_NOT_FOUND: Cannot find package - 10 Causes and Fixes