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

推荐订阅源

博客园 - 【当耐特】
WordPress大学
WordPress大学
T
The Exploit Database - CXSecurity.com
博客园_首页
MyScale Blog
MyScale Blog
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
F
Full Disclosure
V
V2EX
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News: Ask HN
Hacker News: Ask HN
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Martin Fowler
Martin Fowler
PCI Perspectives
PCI Perspectives
S
Security @ Cisco Blogs
Recorded Future
Recorded Future
Help Net Security
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
Microsoft Azure Blog
Microsoft Azure Blog
K
Kaspersky official blog
G
GRAHAM CLULEY
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
CERT Recently Published Vulnerability Notes
U
Unit 42
T
Tor Project blog
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
MongoDB | Blog
MongoDB | Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

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
React Hooks: What's going to happen to react context?
2018-12-17 · via Kent C. Dodds Blog

Earlier this year, the React team introduced the first official context API. I blogged about that new API and people got sufficiently and reasonably hyped.

One common complaint that I knew people were going to have when applying it practically was the fact that the context consumer is a render-prop based API. This can lead to a lot of nesting when you need to consume multiple contexts and other render-prop based APIs as well (for logic reuse). So I addressed that in the blog post by suggesting that you could combine all of the render-prop based APIs into a single function component and consume that:

const ThemeContext = React.createContext('light')
class ThemeProvider extends React.Component {
	/* code */
}
const ThemeConsumer = ThemeContext.Consumer
const LanguageContext = React.createContext('en')
class LanguageProvider extends React.Component {
	/* code */
}
const LanguageConsumer = LanguageContext.Consumer

function AppProviders({ children }) {
	return (
		<LanguageProvider>
			<ThemeProvider>{children}</ThemeProvider>
		</LanguageProvider>
	)
}

function ThemeAndLanguageConsumer({ children }) {
	return (
		<LanguageConsumer>
			{(language) => (
				<ThemeConsumer>
					{(theme) => children({ language, theme })}
				</ThemeConsumer>
			)}
		</LanguageConsumer>
	)
}

function App() {
	return (
		<AppProviders>
			<ThemeAndLanguageConsumer>
				{({ theme, language }) => (
					<div>
						{theme} and {language}
					</div>
				)}
			</ThemeAndLanguageConsumer>
		</AppProviders>
	)
}

As much as this solution works thanks to the composability of React components, I'm still not super thrilled with it. And I'm not the only one:

We've heard feedback that adopting the new render prop API can be difficult in class components. So we've added a convenience API to consume a context value from within a class component.  —React v16.6.0: lazy, memo and contextType

This new convenience API means that if you use a class component and you're only consuming one context, you can simply define a static property called contextType and assign it to the context you want to consume, then you can access the context via this.context. It's pretty neat and a nice trick for common cases where you only consume a single context.

I've used this convenience API and I love it. But I'm even more excited about the implications that React Hooks have for the future of React context. Let's rewrite what we have above with the upcoming (ALPHA!) useContext hook:

const ThemeContext = React.createContext('light')
class ThemeProvider extends React.Component {
	/* code */
}
const LanguageContext = React.createContext('en')
class LanguageProvider extends React.Component {
	/* code */
}

function AppProviders({ children }) {
	return (
		<LanguageProvider>
			<ThemeProvider>{children}</ThemeProvider>
		</LanguageProvider>
	)
}

function App() {
	const theme = useContext(ThemeContext)
	const language = useContext(LanguageContext)
	return (
		<div>
			{theme} and {language}
		</div>
	)
}

ReactDOM.render(
	<AppProviders>
		<App />
	</AppProviders>,
	document.getElementById('root'),
)

WOWZA! As powerful as the render-prop based consumers are, this is even easier to read, understand, refactor, and maintain! And it's not just less code for less code's sake. Besides, often when we reduce the amount of code we also reduce the clarity of communication that code can give to us. But in this case, it's less code and it's easier to understand. I think that's a big win and a huge feature of the new hooks API.

Another big feature of React hooks is the fact that it's completely opt-in and backward compatible. I'm given such a huge amount of comfort knowing that Facebook can't make decisions that will cause grief to the engineers who are working on the oldest and one of the largest React codebases in the world. The fact that React has incrementally taken us to this new world of hooks is just fantastic. Thanks React team! Looking forward to the official release!

Conclusion

One of the coolest things about React is that it allows us to focus on solving real-world problems without normally having to get too close to the implementation of things. It's been a long time since I had to deal with cross-browser or performance issues with any degree of regularity. And now React is taking it even further and simplifying things so the code that I do write is simpler to read, understand refactor, and maintain. I just love that. Makes me wonder if there may be some things I could do about my code to simplify things for other people as well 🤔.

Until next time! Good luck! 👋