Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 42 additions & 5 deletions src/components/MDX/ErrorDecoder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import {useEffect, useState} from 'react';
import {useErrorDecoderParams} from '../ErrorDecoderContext';
import cn from 'classnames';
import {IconError} from '../Icon/IconError';

function replaceArgs(
msg: string,
Expand Down Expand Up @@ -108,12 +109,48 @@ export default function ErrorDecoder() {
}, [errorCode, hasParams, errorMessage]);

return (
<code
<div
className={cn(
'whitespace-pre-line block bg-red-100 text-red-600 py-4 px-6 mt-5 rounded-lg',
'console-block mb-4 text-secondary bg-wash dark:bg-wash-dark rounded-lg mt-5',
isReady ? 'opacity-100' : 'opacity-0'
)}>
<b>{message}</b>
</code>
)}
translate="no"
dir="ltr">
<div className="flex w-full rounded-t-lg bg-gray-200 dark:bg-gray-80">
<div className="px-4 py-2 border-gray-300 dark:border-gray-90 border-r">
<div
className="bg-gray-300 dark:bg-gray-70"
style={{width: '15px', height: '17px'}}
/>
</div>
<div className="flex text-sm px-4">
<div className="border-b-2 border-gray-300 dark:border-gray-90 text-tertiary dark:text-tertiary-dark">
Console
</div>
<div className="px-4 py-2 flex">
<div
className="me-2 bg-gray-300 dark:bg-gray-70"
style={{width: '60px', height: '17px'}}
/>
<div
className="me-2 hidden md:block bg-gray-300 dark:bg-gray-70"
style={{width: '60px', height: '17px'}}
/>
<div
className="hidden md:block bg-gray-300 dark:bg-gray-70"
style={{width: '60px', height: '17px'}}
/>
</div>
</div>
</div>
<div className="grid grid-cols-1 divide-y divide-gray-300 dark:divide-gray-70 text-base">
<div className="ps-4 pe-2 pt-1 pb-2 grid grid-cols-[18px_auto] font-mono rounded-b-md bg-red-30 text-red-50 dark:text-red-30 bg-opacity-5">
<IconError className="self-start mt-1.5 text-[.7rem] w-6" />
<div className="px-2 pt-1 whitespace-break-spaces text-code leading-tight">
{message}
</div>
</div>
</div>
</div>
);
}
127 changes: 127 additions & 0 deletions src/content/errors/321.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<Intro>

This page explains this React error and common ways to fix it.

</Intro>

The full text of the error is:

<ErrorDecoder />

<Note>

In the minified production build of React, full error messages are replaced with short codes to reduce bundle size. We recommend using the development build when debugging, as it includes additional warnings and debug information.

</Note>

## What This Error Means {/*what-this-error-means*/}

This error occurs when a Hook is called in a way that violates the [Rules of Hooks](/reference/rules/rules-of-hooks):

```js {4}
export default function Counter() {
function handleClick() {
// 🔴 Invalid Hook call!
const [count, setCount] = useState(0);
setCount(count + 1);
}

return <button onClick={handleClick}>Click me</button>;
}
```

You can only call Hooks at the top level of a function component or a custom Hook. React tracks Hooks by associating them with the component that is currently rendering. When you call a Hook and no component is rendering, React cannot associate the Hook with a component, and throws this error.

The most common cause is calling a Hook outside a function component. For example, inside an event handler, a class component, or a regular function. Another common cause is having **multiple copies of React** loaded in your app, which is a build configuration problem, not a coding mistake.

[See the examples below for common causes and how to fix them.](#common-causes)

## Common Causes {/*common-causes*/}

### Calling a Hook outside the body of a function component {/*calling-a-hook-outside-the-body-of-a-function-component*/}

React requires you to call Hooks at the top level of a function component or a custom Hook—not inside event handlers, nested functions, or class components.

Here is an example of code that would trigger this error:

<Sandpack>

```js {expectedErrors: {'react-compiler': [7]}}
import { useState } from 'react';

export default function Counter() {
function handleClick() {
// 🔴 useState is called inside an event handler, not the component body
// eslint-disable-next-line react-hooks/rules-of-hooks
const [count, setCount] = useState(0);
setCount(count + 1);
}

return <button onClick={handleClick}>Click me</button>;
}
```

</Sandpack>

To fix this, move the Hook call to the top level of your component:

<Sandpack>

```js
import { useState } from 'react';

// ✅ Fixed: useState is called at the top level of the component
export default function Counter() {
const [count, setCount] = useState(0);

function handleClick() {
setCount(count + 1);
}

return <button onClick={handleClick}>Count: {count}</button>;
}
```

</Sandpack>

The same rule applies to class components—you cannot use Hooks in class components. If you need state or other React features in a class component, [convert it to a function component](/reference/react/Component#alternatives).

### Multiple copies of React in your app {/*multiple-copies-of-react*/}

If your project uses a monorepo, `npm link`, or a third-party package that bundles its own copy of React, you can end up with two separate copies of React loaded at the same time. When this happens, the copy of React that your component uses is different from the copy that `react-dom` uses, and Hooks break because React can't track them across copies.

To check if this is your problem, run the following from your project root:

```bash
npm ls react
```

If you see more than one entry for `react`, you have duplicate copies. You can also add a temporary log to confirm. Add this at the top of your component file:

```js
import React from 'react';
console.log(React === window.React); // false means duplicates
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think here we need a caveat, or further instruction, as in, you first need to identify where a different React version might be used. And assign that React version to window.React.

```

If you're using webpack, you can fix this by adding a resolve alias in your webpack config:

```js
// webpack.config.js
module.exports = {
resolve: {
alias: {
react: require.resolve('react'),
'react-dom': require.resolve('react-dom'),
},
},
};
```

If you're using Vite, add a similar alias in your Vite config. For other bundlers, consult their documentation on how to configure module aliases.

## Related Documentation {/*related-documentation*/}

- [Rules of Hooks](/reference/rules/rules-of-hooks)
- [`useState`](/reference/react/useState)
- [Your First Component](/learn/your-first-component)
- [Reusing Logic with Custom Hooks](/learn/reusing-logic-with-custom-hooks)
16 changes: 13 additions & 3 deletions src/pages/errors/[errorCode].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,33 @@ interface ErrorDecoderProps {
content: string;
toc: string;
meta: any;
isCustom: boolean;
}

export default function ErrorDecoderPage({
errorMessage,
errorCode,
content,
toc,
isCustom,
}: InferGetStaticPropsType<typeof getStaticProps>) {
const parsedContent = useMemo<React.ReactNode>(
() => JSON.parse(content, reviveNodeOnClient),
[content]
);
const parsedToc = useMemo(
() => (isCustom ? JSON.parse(toc, reviveNodeOnClient) : []),
[toc, isCustom]
);

return (
<ErrorDecoderContext value={{errorMessage, errorCode}}>
<Page
toc={[]}
toc={parsedToc}
meta={{
title: errorCode
? `Minified React error #${errorCode}`
: 'Minified Error Decoder',
? `React error #${errorCode}`
: 'React Error Decoder',
}}
routeTree={sidebarLearn as RouteItem}
section="unknown">
Expand Down Expand Up @@ -117,11 +124,13 @@ export const getStaticProps: GetStaticProps<ErrorDecoderProps> = async ({
// Read MDX from the file.
let path = params?.errorCode || 'index';
let mdx;
let isCustom = true;
try {
mdx = fs.readFileSync(rootDir + '/' + path + '.md', 'utf8');
} catch {
// if [errorCode].md is not found, fallback to generic.md
mdx = fs.readFileSync(rootDir + '/generic.md', 'utf8');
isCustom = false;
}

const {content, toc, meta} = await compileMDX(mdx, path, {code, errorCodes});
Expand All @@ -131,6 +140,7 @@ export const getStaticProps: GetStaticProps<ErrorDecoderProps> = async ({
content,
toc,
meta,
isCustom,
errorCode: code,
errorMessage: code ? errorCodes[code] : null,
},
Expand Down
Loading