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

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

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's ⚛️ new Context API
Kent C. Dodds 🏹 @kentcdodds · 2018-02-05 · via Kent C. Dodds Blog

This article is only kept around for historical purposes. The context API isn't "new" and there are better ways to use it (via hooks).

Curious about happend to the context API when React hooks were released? Read all about it here: https://kentcdodds.com/blog/react-hooks-whats-going-to-happen-to-react-context

Have you heard of the context API in React? If you've heard of it, are you like many others afraid to use it directly because you saw this in the official docs:

search result of context on the official react documentation site

The first result of that search is showing "Why Not To Use Context". Doesn't inspire a whole lot of confidence in the context API. To make things even more concerning, that section says:

If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.

So why use context?

Have you ever experienced the pain of trying to get state from the top of your react tree to the bottom? This pain you're feeling is called "prop drilling" and it's super annoying. You wind up having to pass props through components that don't care about the data just so you can send it down to components that do care. And as you move components around this pain is magnified.

You could actually use a regular JavaScript module to avoid these problems. Just put the data in a singleton module and poof, it's accessible/importable anywhere. But then you have trouble with updates (you have to implement an event emitter to notify subscribers when there are updates), and server side rendering can be problematic with singletons as well.

So this is where state management libraries like redux come into play (specifically react-redux). They allow you to get data from the store easily anywhere in the tree. All you have to do is use this thing called a <Provider /> and magically your store data is accessible by any component that is "connected."

What if I told you that the <Provider /> is using this experimental context feature 😱 Indeed it is! The provider component puts the data into context, and the connect Higher Order Component pulls the data out of context. So in reality, redux isn't allowing your data to be accessible anywhere... context is!

So, why should you use context? Well, you probably already are and loving it! Even if you're not using context directly, your app is making use of it via react-redux, MobX-react, React Router, glamorous, and more!

Context Reborn

So we love context, but remember that warning that "it is likely to break in future releases of React"? IT'S COMING! And you're going to love it!

Over a month ago, the React team created a new RFCs repository inspired by Yarn's, Rust's, and Ember's. The first pull request to that repository is from Andrew Clark (react core team member) and it's called "New version of context". In it, Andrew outlines what the new version of context will be. There's interesting discussion in there. A few days later, Andrew opened a PR to React called "New context API".

So what does it look like? Whelp, it's about a million times more intuitive than the old context API. Here's the simplest useful example I can come up with:

Error embedding https://codesandbox.io/s/n4r0qq898j

Here's an even simpler version so you don't have to open the codesandbox:

const ThemeContext = React.createContext('light')
class ThemeProvider extends React.Component {
	state = { theme: 'light' }
	render() {
		return (
			<ThemeContext.Provider value={this.state.theme}>
				{this.props.children}
			</ThemeContext.Provider>
		)
	}
}

class App extends React.Component {
	render() {
		return (
			<ThemeProvider>
				<ThemeContext.Consumer>
					{(val) => <div>{val}</div>}
				</ThemeContext.Consumer>
			</ThemeProvider>
		)
	}
}

You might notice in my example I'm using the render prop Consumer component (the best!), but if that's not your jam, you could easily implement a Higher Order Component or something else using the context API (which is why it's the best).

The new context API consists of three main parts:

  • React.createContext which is passed the initial value (and optionally a fancy opt-out function that uses a bitmask). This returns an object with a Provider and a Consumer
  • The Provider component is used higher in the tree and accepts a prop called value (which can be anything).
  • The Consumer component is used anywhere below the provider in the tree and accepts a prop called "children" which must be a function that accepts the value and must return a react element (JSX).

I'm extremely excited about this API. The React team will remove the warning about context being an experimental feature because it's now a "first-class feature" of the framework. This means that people will hopefully be less concerned about using it to help solve the prop-drilling problem in their apps which hopefully will help people not feel like they have to reach for redux so early to solve that pain and they can instead stick with vanilla React for longer (or perhaps, Unstated by James Kyle is the solution we've all been waiting for).

I recently tweeted:

People's fixation with keeping render methods small aggravates the "prop drilling problem" which makes folks want redux to help alleviate it

4 63

So I think if we avoid prematurely and arbitrarily breaking up render methods, we'll feel this pain even less. But even when we do feel it, we'll have a solid, core React API to lean on to help us avoid the problem.

Practical Context

One question that I've seen a lot about the new context API (or the render prop pattern in general) is how to compose providers and consumers together. When you put a bunch of render prop components together in a single render method, things can get... nested:

So what can we do to avoid this? If it bothers you, then you can solve it the same way you solve the problem in regular JavaScript: utility functions/components. Here's an example:

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>
	)
}

class App extends React.Component {
	render() {
		return (
			<AppProviders>
				<ThemeAndLanguageConsumer>
					{({ theme, language }) => (
						<div>
							{theme} and {language}
						</div>
					)}
				</ThemeAndLanguageConsumer>
			</AppProviders>
		)
	}
}

The goal here is to take common use cases and make special functions/components to make those use cases more ergonomic. Just like you do in regular JavaScript! Makes sense right? I hope it does anyway 😅

I have another example here that really shows how bad the nesting can get and how to use a utility called react-composer by jmeas to make it great:

Error embedding https://codesandbox.io/s/92pj14134y

I should mention that I don't expect you to need to nest render props components a whole lot in practice. Whenever you do, you can create a simple component that composes them together and use that one instead.

Conclusion

Like I said, I'm super stoked about this API. It's currently unreleased, but will be included in the next minor React release. Don't worry, the old context API will continue to work until the next major release, so everyone should have time to migrate. And don't forget that the React team has over 50,000 react components at Facebook they need to consider when making changes like this. There will quite probably be a codemod released to automatically update most everyone's code (as there often is).

I'm excited about what this new API has to offer. As I noted on twitter recently (in response to Dan Abramov's tweet):

Kent C. Dodds 🏹 avatar

Kent C. Dodds 🏹 @kentcdodds

@dan_abramov That's one thing that excites me about the API improvement (in addition to other changes coming). So many new patterns will emerge out of this stuff. Ways of doing things we haven't considered before!!

1 12

So much to look forward to! Good luck! 👍