AsyncLocalStorage vs. React Context

Rate this content
Bookmark

AsyncLocalStorage is a modern API which has landed in many JavaScript runtimes. It allows developers to pass a value to a callback function without needing to drill through a direct reference. In this, it is similar to React’s Context. However, although they have a somewhat related purpose, particularly in a React Server Components world, there are meaningful differences and a suitable time to use one over the other.

This talk has been presented at React Summit 2024, check out the latest edition of this React Conference.

FAQ

Server actions in a React app handle tasks such as mutating databases or interacting with file systems. They run exclusively on the server and are not available on the client, allowing for more complex operations to be performed server-side.

To get started with async local storage, import the module from 'node:async_hooks', create an instance of the storage (often abbreviated as ALS), and call the run method on the storage instance with a value and a callback function. Within the callback function, you can call the getStore method to retrieve the value.

The standardization of async local storage is handled by WinterCG, a community group that focuses on standardizing JavaScript APIs across various JavaScript runtimes such as Cloudflare Workers, Deno, Vercel, and Netlify.

Both async local storage and React context involve creating an instance, providing a value in a parent context, and retrieving that value in a child context.

Async local storage is a standardized API, initially developed in Node.js and standardized by WinterCG, which allows for storing data specific to a particular asynchronous operation.

React context allows for sharing values between a parent and child component. You create an instance of the context, provide a value in the parent component, and use a function in the child component to retrieve that value.

No, React context cannot be used within server actions because server actions do not retain any information about parent or child components.

Async local storage is useful in complex applications where you need to retrieve values from a parent further up the execution chain without passing them through multiple layers, or when handling concurrent JavaScript operations.

Async local storage serves as a bridge between the platform and the React app, allowing for seamless data transfer and operations between the two, while React context is primarily used for client-side state management.

A modern React app with React 18 involves the client making a request to the edge, which gets turned into a React Server Components request. This request is sent to regional compute, translated into a serialized DOM, and sent back to the edge. The edge turns this into HTML, which is then sent to the client. The client fetches the JavaScript for interactivity and performs client-side hydration.

 Greg Brimble
Greg Brimble
8 min
18 Jun, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Today's Talk explores the concepts of async local storage and React context. Async local storage is a useful API for retrieving values from a parent component without passing them through multiple components. React context, on the other hand, allows for the creation of context instances in parent components and consumption in child components. The Talk also discusses server actions in React, their limitations, and the use of async local storage in server actions, with an example Cloudflare worker handling web requests and authentication.

1. Introduction to Async Local Storage

Short description:

Today, I'm going to talk about async local storage and React context. Async local storage, standardized by WinterCG, is a useful API for complex applications that need to retrieve values from a parent component. It allows you to avoid passing values through multiple components. To use async local storage, you import the module from node async hooks, create an instance, and call the run method with a value and a callback function. Then, within the callback function, you can use the get store method to retrieve the value.

Hi, thanks for tuning in. Today I'm going to be talking about async local storage and React context. Async local storage is a somewhat recently standardized API, standardized by WinterCG having come from Node.js. WinterCG is the community group that's responsible for standardizing JavaScript APIs across these new JavaScript run times, things like Cloudflare workers, Deno, Vercel, Netlify, et cetera.

If you haven't seen it before, this is how you get started with async local storage. You first import the module from something called node async hooks. You can create an instance of the storage, often abbreviated down to ALS. You can then call a run method on that storage instance, providing a value and a callback function. And then from within that callback function, you can call this get store method on your store instance. And that will return the value that you passed previously when you called run.

You see, it's pretty straightforward, and it's mostly useful if you have a complex application that you need to get values from like a parent way further earlier in your execution chain, and you don't want to drill it all the way through your app, or if you're handling concurrent JavaScript or something like that.

2. Introduction to React Context

Short description:

React context has a familiar API. You create an instance of your context in a parent component, provide a value, and then call a child component to consume it. In a modern React app, the client makes a request to the edge, which is turned into a React server components request and sent to regional compute. The returned serialized DOM is translated into HTML through server-side rendering and delivered to the client. The client fetches the JavaScript from the edge, hydrates the HTML into an interactive React app, and can perform server actions that mutate the database or file system.

Similarly, React context has a very familiar API. So, again, you import from the React module. You create an instance of your context. Within a parent component, you can provide a value and then call some child component, and then that child component can use a function to retrieve that value from the parent. Like I say, very similar to ALS, and in fact, there's basically just those three points, creating the instance, a parent that calls it with a value and a child that can consume it.

So, if we just sort of take a step back and remind ourselves of exactly how React app gets rendered these days, because it has changed a bit with React 18 and React components. So, this is just sort of an example of how you might render a modern React app.

The client makes a request to the edge. This then gets turned into an RSC, React server components request, and gets sent to some sort of regional compute. This is near to where your database or upstream or whatever it is happens to be. This then does some serious server things. This is maybe speaking to a file system or, like I say, a database or a SQLite thing or whatever it is. And this all happens far away from user in regional compute. The RC then is translated into some sort of like serialized DOM. It's a very interesting format. Basically it allows for streaming, that sort of thing. This goes back to the edge. The edge then turns this into HTML through server side rendering, and sends it back to the client.

The client has then got a HTML page, but they need to actually fetch the JavaScript to make it interactive. So, they request that from the edge. And because it's the edge, it just delivers the asset straight back to the client fast and speedy. Client then does client side hydration. That's actually turning the HTML that it has on the page at the moment into an actual interactive React app. And then we might actually want to take action. So, I might click submit on a form. And that's going to send a server action to over the network sending my form values. It's gonna be proxied through the edge and end up in the region. And again, that's going to be able to do some serious server things. That might be mutating my database or hitting the file system. Whatever.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Simplifying Server Components
React Advanced 2023React Advanced 2023
27 min
Simplifying Server Components
Top Content
Watch video: Simplifying Server Components
React server components simplify server-side rendering and provide a mental model of components as pure functions. Using React as a library for server components allows for building a basic RSC server and connecting it to an SSR server. RSC responses are serialized virtual DOM that offload code from the client and handle interactivity. The client manifest maps serialized placeholders to real components on the client, enabling dynamic rendering. Server components combine the best of classic web development and progressive enhancement, offering the advantage of moving logic from the client to the server.
Exploring React Server Component Fundamentals
React Day Berlin 2023React Day Berlin 2023
21 min
Exploring React Server Component Fundamentals
Top Content
Watch video: Exploring React Server Component Fundamentals
This Talk introduces React Server Components (RSC) and explores their serialization process. It compares RSC to traditional server-side rendering (SSR) and explains how RSC handles promises and integrates client components. The Talk also discusses the RSC manifest and deserialization process. The speaker then introduces the Waku framework, which supports bundling, server, routing, and SSR. The future plans for Waku include integration with client state management libraries.
And Now You Understand React Server Components
React Summit 2024React Summit 2024
27 min
And Now You Understand React Server Components
Top Content
In this Talk, Kent C. Dodds introduces React Server Components (RSCs) and demonstrates how to build them from scratch. He explains the process of integrating RSCs with the UI, switching to RSC and streaming for improved performance, and the benefits of using RSCs with async components. Dodds also discusses enhancements with streaming and server context, client support and loaders, server component rendering and module resolution, handling UI updates and rendering, handling back buttons and caching, and concludes with further resources for diving deeper into the topic.
A Practical Guide for Migrating to Server Components
React Advanced 2023React Advanced 2023
28 min
A Practical Guide for Migrating to Server Components
Top Content
Watch video: A Practical Guide for Migrating to Server Components
React query version five is live and we'll be discussing the migration process to server components using Next.js and React Query. The process involves planning, preparing, and setting up server components, migrating pages, adding layouts, and moving components to the server. We'll also explore the benefits of server components such as reducing JavaScript shipping, enabling powerful caching, and leveraging the features of the app router. Additionally, we'll cover topics like handling authentication, rendering in server components, and the impact on server load and costs.
Server Components: The Epic Tale of Rendering UX
React Summit 2023React Summit 2023
26 min
Server Components: The Epic Tale of Rendering UX
Top Content
Watch video: Server Components: The Epic Tale of Rendering UX
This Talk introduces server components in React, which provide an intermediate format for rendering and offer advantages for both client-side and server-side rendering. Server components reduce bundle size on the client and improve search engine optimization. They abstract the rendering process, allowing for faster rendering and flexibility in choosing where to render components. While server components are still in the experimental stage, Next.js is a good starting point to try them out.
RSCs In Production: 1 Year Later
React Summit 2024React Summit 2024
24 min
RSCs In Production: 1 Year Later
This Talk explores the experience of shipping server components in production and highlights the benefits and challenges of using Server Components in Next.js apps. The Talk discusses the deployment of UploadThing and the use of AppRouter for safe production usage. It delves into the implementation of different layouts, data fetching, and code centralization for improved performance. The Talk also covers the use of server components for performance optimization and latency handling. Additionally, it explores the use of Edge and Lambda for partial pre-rendering and the challenges faced with webpack performance and hydration. Overall, the Talk emphasizes the benefits and challenges of working with Server Components in Next.js applications.

Workshops on related topic

Mastering React Server Components and Server Actions in React 19
React Summit US 2024React Summit US 2024
150 min
Mastering React Server Components and Server Actions in React 19
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Calling all React developers! Join us for an immersive 4-hour workshop diving deep into React Server Components and Server Actions. Discover how these game-changing technologies are revolutionizing web development and learn how to harness their full potential to build lightning-fast, efficient applications.

Explore the world of React Server Components, seamlessly blending server-side rendering with client-side interactivity for unmatched performance and user experience. Dive into React Server Actions to see how they combine client-side interactivity with server-side logic, making it easier to develop interactive applications without traditional API constraints.

Get hands-on experience with practical exercises, real-world examples, and expert guidance on implementing these technologies into your projects. Learn essential topics such as the differences between Server and Client Components, optimizing data fetching, passing data effectively, and maximizing performance with new React hooks like useActionState, useFormStatus and useOptimistic.

Whether you're new to React or a seasoned pro, this workshop will equip you with the knowledge and tools to elevate your web development skills. Stay ahead of the curve and master the cutting-edge technology of React 19. Don't miss out - sign up now and unleash the full power of React!
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
The Gateway to Backend: A Frontend Developer's Guide to Full-Stack Development
React Summit US 2023React Summit US 2023
160 min
The Gateway to Backend: A Frontend Developer's Guide to Full-Stack Development
Top Content
WorkshopFree
Amy Dutton
Amy Dutton
This workshop will guide you through the product development life cycle of creating a real-world web application. You will learn about React Server Components, building a design system within Storybook, and using frontend development to approach becoming a full-stack developer. The workshop will cover increasing confidence in your application with unit tests and implementing authentication and authorization. You'll have the opportunity to work through product features and examine a real-world RedwoodJS project, gaining valuable experience in real-world product development. RedwoodJS makes it simple to approach full-stack development, and this workshop will give you the skills you need to create your own real-world web applications.
Advanced Application Deployment Patterns with React Server Components (feat. a DIY RSC Framework)
React Summit US 2023React Summit US 2023
104 min
Advanced Application Deployment Patterns with React Server Components (feat. a DIY RSC Framework)
Top Content
WorkshopFree
 Greg Brimble
Greg Brimble
The developer ecosystem is always moving fast and this year has proved no exception. React Server Components can offer a significant improvement to developer experience and to application performance. But I think it's fair to say that this new server-first paradigm can be tricky to wrap your head around!In the first half of this workshop, we'll explore React Server Components from the ground-up: building our own mini meta-framework to help us understand how RSCs work. We'll discover exactly what is produced by an RSC build and we'll connect those pieces together to form a full application.Next, we'll deploy it! Cloudflare have also had a busy year too — Smart Placement, in particular, is a new technology that we've developed which fits the RSC model perfectly. We'll explore why that makes sense for our workshop app, and we'll actually deploy it onto the Cloudflare Developer Platform.Finally, we'll build out our app a little further, using D1 (our serverless SQL database) to really show off the React Server Component's power when combined with Smart Placement.You should come away from this workshop with a greater understanding of how React Server Components work (both behind-the-scenes and also how you as a developer can use them day-to-day), as well as insight into some of the new deployment patterns that are now possible after recent innovations in the platform space.
Building Reusable Server Components in NextJS
React Summit US 2023React Summit US 2023
88 min
Building Reusable Server Components in NextJS
Workshop
Will Bishop
Mettin Parzinski
2 authors
React continues to evolve their beta capability, React Server Components, and they're continuing to further develop them in partnership with frameworks like NextJS.In this workshop, attendees will learn what React Server Components are, how to effectively build and use them in NextJS, and focus on one of the major advantages of React/NextJS: reusability through components.We will also cover related beta technologies enabled by the `app` directory, such as nested layouts and server actions (alpha/experimental capability).Join us for this hands-on, 120 minute workshop!Technologies:
React, JavaScript/Typescript, NextJS, Miro
React Server Components Unleashed: A Deep Dive into Next-Gen Web Development
React Day Berlin 2023React Day Berlin 2023
149 min
React Server Components Unleashed: A Deep Dive into Next-Gen Web Development
Workshop
Maurice de Beijer
Maurice de Beijer
Get ready to supercharge your web development skills with React Server Components! In this immersive, 3-hour workshop, we'll unlock the full potential of this revolutionary technology and explore how it's transforming the way developers build lightning-fast, efficient web applications.
Join us as we delve into the exciting world of React Server Components, which seamlessly blend server-side rendering with client-side interactivity for unparalleled performance and user experience. You'll gain hands-on experience through practical exercises, real-world examples, and expert guidance on how to harness the power of Server Components in your own projects.
Throughout the workshop, we'll cover essential topics, including:- Understanding the differences between Server and Client Components- Implementing Server Components to optimize data fetching and reduce JavaScript bundle size- Integrating Server and Client Components for a seamless user experience- Strategies for effectively passing data between components and managing state- Tips and best practices for maximizing the performance benefits of React Server Components