Using the Proxy API for State Management

Rate this content
Bookmark
The video covers using the JavaScript Proxy API for state management, highlighting the benefits of using proxies to observe and handle changes in objects. It explains basic proxy methods like get and set traps, and the role of the Reflect object in forwarding operations to the original object. The talk includes a demo on creating a proxy to observe changes to an object, emphasizing how proxies can be used like normal objects. It mentions the importance of avoiding proxies on primitive objects and introduces Taits, a state management library that uses the proxy API. The video also touches on the performance implications of proxies and compares them to other methods like object.observe and object.defineProperty.

From Author:

With so many libraries to choose from for state management, why not add one more? The ECMAScript Proxy API enables you to intercept and redefine how an object operates. Let's explore how you might use the Proxy API for state management!

This talk has been presented at JSNation Live 2021, check out the latest edition of this JavaScript Conference.

FAQ

Will Johnston is a developer advocate on WP Engine's DevRel team with extensive experience in web and back-end development, particularly in the Node.js, JavaScript, and TypeScript ecosystems.

A JavaScript Proxy is an object that allows you to intercept and customize operations performed on another object, such as property lookups, assignments, and function invocations. It provides a way to define custom behavior for fundamental operations on objects.

Proxies are similar to object.observe and object.defineProperty in that they allow you to observe and define custom behavior on objects. However, proxies are more feature-rich and provide a broader range of capabilities for intercepting operations on objects.

The Reflect object is used to forward operations to the original object in a proxy. This ensures that the original operations are performed correctly and helps avoid issues related to inheritance and other complexities.

'Get' and 'set' traps are methods in a proxy handler that intercept property access and assignment operations. The 'get' trap intercepts property access, while the 'set' trap intercepts property assignments.

The receiver provides the proper context to the Reflect object within a proxy handler, ensuring that operations are forwarded correctly to the original object.

Taits is a small state management library that uses the proxy API to observe changes to state objects. It allows you to create proxies and subscribe to changes on specific paths within those proxies.

While proxies may introduce some performance overhead compared to normal JavaScript operations, they are generally fast enough for most use cases. However, for highly performance-sensitive applications, alternatives may be considered.

A simple proxy handler in JavaScript can be created with 'get' and 'set' traps. For example: ```javascript const handler = { get: (target, property) => { console.log(`Getting ${property}`); return target[property]; }, set: (target, property, value) => { console.log(`Setting ${property} to ${value}`); target[property] = value; return true; } }; const proxy = new Proxy({}, handler); proxy.name = 'Will'; console.log(proxy.name); ```

To avoid creating a proxy on a primitive object, you can check the type of the value before creating the proxy. For example: ```javascript if (typeof value !== 'object' || value === null) { return value; } ```

Will Johnston
Will Johnston
27 min
09 Jun, 2021

Comments

Sign in or register to post your comment.

Video Transcription

1. Introduction to Proxies

Short description:

Hi, I'm Will Johnston, a developer advocate on WP Engine's DevRel team. Today, I'll discuss using proxies or the JavaScript Proxy API for state management.

♪♪ Hi, I'm Will Johnston. I'm a developer advocate on WP Engine's DevRel team, and I'm here today to talk to you about how you might use proxies or the JavaScript Proxy API for state management. Proxies, if you're unfamiliar, are a way that you can observe some of the underlying operations on objects within JavaScript. So if you're familiar with object.observe, which doesn't exist anymore, but that was kind of the precursor to proxies. And if you're also familiar with property descriptors or object.defineProperty, that's a similar thing to proxies. Proxies just enable a little bit more full features.

2. Introduction to Proxies (continued)

Short description:

I have been writing code since I was about 10 years old. I got interested in proxies to understand what's happening underneath. Proxy methods like get and set traps are simple and easy to grasp. Reflect is used to forward operations onto the original object and avoid inheritance issues. Let's create a basic demo using proxy to observe changes to an object. We intercept get and set operations and log them. We can use the proxy like a normal object.

A little bit about myself. I have been writing code since I was about 10 years old. In high school, I got a job doing some web programming with Python, and I really fell in love with software at that time and software development, and I've been a constant learner since then. I spent most of my career working on the web and back-end, and over the past few years, probably six to eight years, I've been working mostly with Node in the JavaScript and TypeScript ecosystem.

So, I really got interested in proxies because I've done a fair amount of .NET and C Sharp code, and in C Sharp, you have a concept of getters and setters on an object, and it allows you to stealthily poke into different operations on that object, and proxies function in a similar manner but for JavaScript. So, I got really interested into proxies to try to figure out how I can make that work because I really love when you can just use objects as you normally would, but underneath, you can understand exactly what's happening.

So, there are plenty of proxy methods, and proxy methods are used to set up traps, so you can observe some of the inherent ability for JavaScript to be performing different functions, so that's what a trap is. We're going to use the get and set traps today because those are simple and easy to grasp, and I'm not trying to go too far in depth with the short time that we have.

Something to know, when you're using proxy, you really also need to be using reflect, so the reflect object is used to forward all the operations onto the original object, so if you think of proxy is in front and you're listening to the set method, when somebody tries to set, you want to use the reflect object to eventually forward that operation on and actually set the value on that object. The reason you do this is related to avoiding this in inheritance issues, so if you create a proxy and then you try to inherit from it and you don't use reflect, you're going to get some wonky functionality where you're actually changing the original object, not the inherited object.

So let's just start with a basic demo, let's get a state object up using proxy to observe changes to that object, so we will, I like to create a proxy handler, it's the easiest way, I know that I'm going to eventually have to create a new object, a new proxy, and we will create an object and our handler is gonna be our proxy handler, so we know that our proxy handler is going to be a type proxy handler and that's where we have our get and our set methods, so let's create those now, target property and set target property value. So the get method just returns the target, the property at a certain target and the set method sets the value of a property on a target, so in here, we'll say getting property value value to be in here, we will say setting property oops and we will use the reflect API and this is how we can, it just mimics the proxy API directly. And allows us to not have to worry about what actually happens underneath, we just want to poke in where we care about it and observe the change. There's one additional piece we care about here and that is called the receiver and we want to add that in there. The receiver is going to provide the reflect object with that proper context. So here we have our get, our set, we are just intercepting these operations and logging, pretty simple.

For this, let's create on our state, a person, we'll say first name, Will. And let's go ahead and just add a last name too. Johnston, all right. And then, in order to actually see what's going on here, we will have to console.log, state.person.firstname. So what we expect here is it's going to log, you know, getting person on here. You might expect it to log getting firstname as well. We'll see whether it does in a second. Spoiler alert, it does not. And I'm just going to say here, and I'll call William. So we'll try to set the first name and that's good. All right. So note, when we create this proxy, we can just use state like a normal object. We don't have to care. So if you had, typically you'll use a library that might be using proxy underneath.

QnA

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

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
React Query: It’s Time to Break up with your "Global State”!
React Summit Remote Edition 2020React Summit Remote Edition 2020
30 min
React Query: It’s Time to Break up with your "Global State”!
Top Content
Global state management and the challenges of placing server state in global state are discussed. React Query is introduced as a solution for handling asynchronous server state. The Talk demonstrates the process of extracting logic into custom hooks and fixing issues with state and fetching logic. Optimistic updates with mutation are showcased, along with the benefits of using React Query for data fetching and mutations. The future of global state management is discussed, along with user feedback on React Query. The Talk concludes with an invitation to explore React Query for server state management.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
Jotai Atoms Are Just Functions
React Day Berlin 2022React Day Berlin 2022
22 min
Jotai Atoms Are Just Functions
Top Content
State management in React is a highly discussed topic with many libraries and solutions. Jotai is a new library based on atoms, which represent pieces of state. Atoms in Jotai are used to define state without holding values and can be used for global, semi-global, or local states. Jotai atoms are reusable definitions that are independent from React and can be used without React in an experimental library called Jotajsx.

Workshops on related topic

Rethinking Server State with React Query
React Summit 2020React Summit 2020
96 min
Rethinking Server State with React Query
Top Content
Featured Workshop
Tanner Linsley
Tanner Linsley
The distinction between server state and client state in our applications might be a new concept for some, but it is very important to understand when delivering a top-notch user experience. Server state comes with unique problems that often sneak into our applications surprise like:
- Sharing Data across apps- Caching & Persistence- Deduping Requests- Background Updates- Managing “Stale” Data- Pagination & Incremental fetching- Memory & Garbage Collection- Optimistic Updates
Traditional “Global State” managers pretend these challenges don’t exist and this ultimately results in developers building their own on-the-fly attempts to mitigate them.
In this workshop, we will build an application that exposes these issues, allows us to understand them better, and finally turn them from challenges into features using a library designed for managing server-state called React Query.
By the end of the workshop, you will have a better understanding of server state, client state, syncing asynchronous data (mouthful, I know), and React Query.
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
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