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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

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 Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode Profile a React App for Performance
Rendering a function with React
2017-11-13 · via Kent C. Dodds Blog

This "feature" was removed from React 16, so please don't rely on it. That said, this is kinda fun so keep reading!

This week I was working on an internal module at PayPal and had to do something kinda sorta-hacky with React. I thought You'd be interested to hear what I learned.

No, this isn't about render props. If you were hoping for that... callback later 😉

I see what you did there

Context

So react-i18n (not the npm one... one we made at PayPal internally) has this API that I call "sorta-curried". I wrote about it a bit in my last newsletter.

So here's an example:

import getContent, { init } from 'react-i18n'
init({
	content: {
		pages: {
			home: {
				nav: {
					about: 'About',
					contactUs: 'Contact us',
				},
			},
		},
	},
})

// here's the sorta-curried part...
// These all result in exactly the same thing: "About"
getContent('pages.home.nav.about')
getContent('pages')('home')('nav')('about')
getContent('pages.home')('nav.about')
getContent('pages')('home.nav')('about')
// etc...

There are reasons the API is this way, and I'm not going to go over them all. If you're not a fan of the API, you're not alone_. But there are reasons for the API as it is and that's not what we're going over in this post... In retrospect, it's a bad API and I shouldn't have done it this way 😅

With React

So thinking about this in the context of React:

const getHomeContent = getContent('pages.home')
const ui = (
  <a href="/about">
    {getHomeContent('nav.about')}
  </a>
)
// that'll get you:
<a href="/about">About</a>

So far so good. But, what if you mess up and have a typo?

Before this week, here's what happened:

const ui = (
  <a href="/about">
    {getContent('pages.typo.nav.about')}
  </a>
)
// that'll get you:
<a href="/about">{pages.typo.nav.about}</a>
// note, that's a string of "{" and "}"...
// not jsx interpolation...

The problem

So that's fine. But here's where things get tricky. Because we return a string of {full.path.to.content}, if content is missing or there's a typo you can't call a function on what you get back. If you try, you're calling a function on a string and that'll give you an error that would crash the app. Error boundaries could help with this, though sometimes we call getContent outside of a React context, so that wouldn't help in every case. Anyway, this will break the app:

const getHomeContent = getContent('pages.typo')
const ui = <a href="/about">{getHomeContent('nav.about')}</a>
// 💥 error 💥

Again, this is happening because getContent('pages.typo') will return the string {pages.typo} (to indicate that there's no content at that path and the developer needs to fix that problem to get the content). The issue is that you can't invoke a string but that's what's happening because getHomeContent is a string, not a function.

A solution and a new problem

So the change I made this week makes it so when there's no content at a given path, instead of a string, it returns a "sorta-curried" function (just like it would if you hadn't made the typo). This way you can keep calling it all day long if you want. No problem.

So now this wont throw an error, but we lose rendering the path if there's no content!

const getHomeContent = getContent('pages.typo')
const ui = (
  <a href="/about">
    {getHomeContent('nav.about')}
  </a>
)
// that'll get you:
<a href="/about"></a>

And we want to make sure that we show the missing content so it's more obvious for developers (yes we log to the console as well) and if the world is on fire 🔥🌎🔥🌏🔥🌍🔥 and the content failed to load for some reason, it's better for a button to say {pages.transfer.sendMoney} than to say nothing at all.

So here's where the challenge comes in. Let's rewrite the above to make this more clear:

const getHomeContent = getContent('pages.typo')
const aboutContent = getHomeContent('nav.about')
const ui = <a href="/about">{aboutContent}</a>

aboutContent in this example is a function because the call to getContent had a typo, so we'll never actually find content that matches the full path. So the challenge is how do we make sure that we can render the full path in a situation like this?

Developing the solution

At first I thought I could monkey-patch toString on the content getter function. But that didn't work. I still got this warning from React:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

So I stuck a breakpoint at the line where that error was logged and stepped up the stack to find where the problem was.

> printWarning
> warning
> warnOnFunctionType
> reconcileChildFibers <-- ding ding! 🔔

The reconcileChildFibers function is where I discovered that react will check the children you're trying to render to make sure they're render-able.

Looking through that code, it checks if it's an object first, then it checks if it's a string or number, then an array, then an iterator. If it's none of those things, then it'll throw (for a non-ReactElement object) or warn (for a function, like in our case).

So, in my case, the thing I want to render has to be a function due to the constraints mentioned earlier. So I can't make it work as an object, string, number, or array. But I realized that there's nothing stopping me from making my function iterable (if you're unfamiliar, here's the iterators part of my ES6 workshop recording).

So... I made my function iterable 😉

easy button

const ITERATOR_SYMBOL =
	(typeof Symbol === 'function' && Symbol.iterator) || '@@iterator'

// ...

function iterator() {
	let timesCalled = 0
	// useful logging happens here...
	return {
		next() {
			// this is called twice. Once to get the value, and the second time
			// will report that it's done.
			return { done: timesCalled++ > 0, value: pathAsString }
		},
	}
}

// ...

contentGetterFn[ITERATOR_SYMBOL] = iterator

// ...

I made a handy function for this and created a CodeSandbox demo for you to try out! Enjoy!

You're welcome

The cool thing about this too is that I can log an error with a bunch of context to help the developer figure out what's going on. This is possible because if iterator is called I can assume that React is attempting to render the contentGetterFn.

So yeah, there's my use case for making a function iterable 😉

I hope that's helpful and interesting! Good luck!