惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Don't call a React function component
2019-12-08 · via Kent C. Dodds Blog

Watch "Fix 'React Error: Rendered fewer hooks than expected'" on egghead.io

I got a great question from Taranveer Bains on my AMA asking:

I ran into an issue where if I provided a function that used hooks in its implementation and returned some JSX to the callback for Array.prototype.map. The error I received was React Error: Rendered fewer hooks than expected.

Here's a simple reproduction of that error

import * as React from 'react'

function Counter() {
	const [count, setCount] = React.useState(0)
	const increment = () => setCount((c) => c + 1)
	return <button onClick={increment}>{count}</button>
}

function App() {
	const [items, setItems] = React.useState([])
	const addItem = () => setItems((i) => [...i, { id: i.length }])
	return (
		<div>
			<button onClick={addItem}>Add Item</button>
			<div>{items.map(Counter)}</div>
		</div>
	)
}

And here's how that behaves when rendered (with an error boundary around it so we don't crash this page):

In the console, there are more details in a message like this:

Warning: React has detected a change in the order of Hooks
called by BadCounterList. This will lead to bugs and
errors if not fixed. For more information, read the
Rules of Hooks: https://fb.me/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useState
2. undefined                  useState
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

So what's going on here? Let's dig in.

First off, I'll just tell you the solution:

<div>{items.map(Counter)}</div>
<div>{items.map(i => <Counter key={i.id} />)}</div>

Before you start thinking it has to do with the key prop, let me just tell you it doesn't. But the key prop is important in general and you can learn about that from my other blog post: Understanding React's key prop

Here's another way to make this same kind of error happen:

function Example() {
	const [count, setCount] = React.useState(0)
	let otherState
	if (count > 0) {
		React.useEffect(() => {
			console.log('count', count)
		})
	}
	const increment = () => setCount((c) => c + 1)
	return <button onClick={increment}>{count}</button>
}

The point is that our Example component is calling a hook conditionally, this goes against the rules of hooks and is the reason the eslint-plugin-react-hooks package has a rules-of-hooks rule. You can read more about this limitation from the React docs, but suffice it to say, you need to make sure that the hooks are always called the same number of times for a given component.

Ok, but in our first example, we aren't calling hooks conditionally right? So why is this causing a problem for us in this case?

Well, let's rewrite our original example slightly:

function Counter() {
	const [count, setCount] = React.useState(0)
	const increment = () => setCount((c) => c + 1)
	return <button onClick={increment}>{count}</button>
}

function App() {
	const [items, setItems] = React.useState([])
	const addItem = () => setItems((i) => [...i, { id: i.length }])
	return (
		<div>
			<button onClick={addItem}>Add Item</button>
			<div>
				{items.map(() => {
					return Counter()
				})}
			</div>
		</div>
	)
}

And you'll notice that we're making a function that's just calling another function so let's inline that:

function App() {
	const [items, setItems] = React.useState([])
	const addItem = () => setItems((i) => [...i, { id: i.length }])
	return (
		<div>
			<button onClick={addItem}>Add Item</button>
			<div>
				{items.map(() => {
					const [count, setCount] = React.useState(0)
					const increment = () => setCount((c) => c + 1)
					return <button onClick={increment}>{count}</button>
				})}
			</div>
		</div>
	)
}

Starting to look problematic? You'll notice that we haven't actually changed any behavior. This is just a refactor. But do you notice the problem now? Let me repeat what I said earlier: you need to make sure that the hooks are always called the same number of times for a given component.

Based on our refactor, we've come to realize that the "given component" for all our useState calls is not the App and Counter, but the App alone. This is due to the way we're calling our Counter function component. It's not a component at all, but a function. React doesn't know the difference between us calling a function in our JSX and inlining it. So it cannot associate anything to the Counter function, because it's not being rendered like a component.

This is why you need to use JSX (or React.createElement) when rendering components rather than simply calling the function. That way, any hooks that are used can be registered with the instance of the component that React creates.

So don't call function components. Render them.

Oh, and it's notable to mention that sometimes it will "work" to call function components. Like so:

function Counter() {
	const [count, setCount] = React.useState(0)
	const increment = () => setCount((c) => c + 1)
	return <button onClick={increment}>{count}</button>
}

function App() {
	return (
		<div>
			<div>Here is a counter:</div>
			{Counter()}
		</div>
	)
}

But the hooks that are in Counter will be associated with the App component instance, because there is no Counter component instance. So it will "work," but not the way you'd expect and it could behave in unexpected ways as you make changes. So just render it normally.

Good luck!

You can play around with this in codesandbox:

Edit Don't call function components