Using the Proxy API for State Management

Rate this content
Bookmark

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!

Will Johnston
Will Johnston
27 min
09 Jun, 2021

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk introduces the concept of using proxies in JavaScript for state management. It explores the implementation of proxies, observing properties and creating caches, building the proxy, and observing changes with proxies. The Talk also discusses using the Taits library for state management and the performance implications of proxies. TypeScript and JavaScript are compared, and the results of a poll on their usage are shared.

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
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
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
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
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
An increasing amount of data in our React applications is coming from remote and asynchronous sources and, even worse, continues to masquerade as "global state". In this talk, you'll get the lowdown on why most of your "global state" isn't really state at all and how React Query can help you fetch, cache and manage your asynchronous data with a fraction of the effort and code that you're used to.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
Jotai Atoms Are Just Functions
React Day Berlin 2022React Day Berlin 2022
22 min
Jotai Atoms Are Just Functions
Top Content
Jotai is a state management library. We have been developing it primarily for React, but it's conceptually not tied to React. It this talk, we will see how Jotai atoms work and learn about the mental model we should have. Atoms are framework-agnostic abstraction to represent states, and they are basically just functions. Understanding the atom abstraction will help designing and implementing states in your applications with Jotai

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.
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.
Build a powerful DataGrid in few hours with Ag Grid
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Mike Ryan
Mike Ryan
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
Build a Powerful Datagrid With AG Grid
React Summit 2024React Summit 2024
168 min
Build a Powerful Datagrid With AG Grid
WorkshopFree
Brian Love
Brian Love
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.